Python Tutorial: Measuring risk of a portfolio
Skills:
Data Literacy60%
Key Takeaways
Measuring portfolio risk using Python, calculating variance and standard deviation, and implementing matrix notation for covariance matrices
Full Transcript
let's talk about portfolio risk when you invest in stocks you don't know beforehand what your return will be prices go up and down so there is a degree of uncertainty which implies that stock return is a random variable the extent to which the actual returns are spread around their mean value is called variance here is the official formula for variant it is a great indication of stocks riskiness or volatility you might have come across variants in your statistics class certain stocks have a small variance that means their returns are always close to the mean like the returns distribution here in red sometimes stocks have a high variance and are widely spread around the mean like the distribution here in blue this might be easy to understand for a single asset but how does this work for a portfolio well portfolio variance isn't simply the sum of all variances of the underlying stocks and due to the correlation between the assets it becomes more complicated since the assets in your portfolio correlate ie move together or in the opposite direction you intuitively understand that this will influence the riskiness of your investment that implies that correlation should be an ingredient in your portfolio variance also the individual risk levels of the stocks are part of the calculation as well as the portfolio weights lastly you might come across standard deviation used as an indication of risk this is simply the square root of the variance and both are used in practice suppose I calculate the variance of a portfolio with two stocks the portfolio variance is simply calculated by taking the weights times the variance is Sigma 1 and 2 for stock 1 and 2 respectively I need to add a term to account for correlation between the stocks and that's why I multiply W 1 W 2 Rho the correlation coefficient and the variance is Sigma 1 and 2 this last term is actually what we call the covariance so let's rewrite the formula and insert the covariance instead of the correlation times the variances let's take that last equation from the previous slide this one is long and difficult to work with hence we can write it shorter and smarter if we use some matrix notation it then becomes weights transposed times the covariance matrix times the weights the covariance matrix depicted here in the middle contains two variances on the diagonal and the covariances between acid one and two on the off diagonal terms this is something we can actually implement easily in Python let's start from the beginning by taking the price data again first remember to calculate the daily returns using the percentage change function as we need to calculate variance from our set of returns not from prices then we can let Python calculate our covariance matrix for us very easily so now we almost have all ingredients to calculate the portfolio variance we need to take a short additional step which is to analyze our volatility by multiplying it with 250 which is the amount of trading days in a year don't worry about it for now and you'll learn more about this in the next chapter last we need to weight of our portfolio we have five stocks here so let's create a simple equal weight of portfolio now apply the formula and multiply the transpose weights with the covariance matrix and then with the normal weights again make sure to use the dot multiplier here the numpy dot function takes only two arguments to multiply so start with the covariance matrix with normal weights and then multiply that whole thing with the weights transposed and that gives you the portfolio variance last let's take the square root of the variance to calculate the standard deviation like this let's break
Original Description
Want to learn more? Take the full course at https://learn.datacamp.com/courses/introduction-to-portfolio-analysis-in-python at your own pace. More than a video, you'll learn hands-on coding & quickly apply skills to your daily work.
---
Let's talk about portfolio risk.
When you invest in stocks, you don't know beforehand what your return will be. Prices go up and down, so there is a degree of uncertainty, which implies that stock return is a random variable. The extend to which the actual returns are spread around their mean value is called variance. Here is the official formula for variance. It is a great indication of a stocks' riskiness or volatility. You might have come across variance in your statistics class.
Certain stock have a small variance, that means, their returns are always close the mean, like the returns distribution here in red. Sometimes, stocks have a high variance and are widely spread around the mean like the distribution here in blue. This might be easy to understand for a single asset, but how does this work for a portfolio? Well, portfolio variance isn't simply the sum of all variances of the underlying stocks. Due to correlation between the assets, it becomes more complicated.
Since the assets in your portfolio correlate, i.e. move together or in the opposite directions, you intuitively understand this will influence the riskiness of your investment. That implies that correlation should be an ingredient in your portfolio variance. Also, the individual risk levels of the stocks are part of the calculation, as well as the portfolio weights.
Lastly, you might come across "standard deviation" used as an indication of risk. This is simply the square root of the variance, and both are used in practice.
Supposed I calculate the variance of a portfolio with 2 stocks. The portfolio variance is simply calculated by taking the weight times the variances sigma 1 and 2 for stock 1 and 2 respectively. I need to add a term to account for correlatio
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from DataCamp · DataCamp · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
SQL Server Tutorial: Date manipulation
DataCamp
R Tutorial: Intermediate Interactive Data Visualization with plotly in R
DataCamp
R Tutorial: Adding aesthetics to represent a variable
DataCamp
R Tutorial: Moving Beyond Simple Interactivity
DataCamp
Python Tutorial: Why use ML for marketing? Strategies and use cases
DataCamp
Python Tutorial: Preparation for modeling
DataCamp
Python Tutorial: Machine Learning modeling steps
DataCamp
R Tutorial: The prior model
DataCamp
R Tutorial: Data & the likelihood
DataCamp
R Tutorial: The posterior model
DataCamp
R Tutorial: An Introduction to plotly
DataCamp
R Tutorial: Plotting a single variable
DataCamp
R Tutorial: Bivariate graphics
DataCamp
Python Tutorial: Customer Segmentation in Python
DataCamp
Python Tutorial: Time cohorts
DataCamp
Python Tutorial: Calculate cohort metrics
DataCamp
Python Tutorial: Cohort analysis visualization
DataCamp
R Tutorial: Building Dashboards with flexdashboard
DataCamp
R Tutorial: Anatomy of a flexdashboard
DataCamp
R Tutorial: Layout basics
DataCamp
R Tutorial: Advanced layouts
DataCamp
Python Tutorial: Time Series Analysis in Python
DataCamp
Python Tutorial: Correlation of Two Time Series
DataCamp
Python Tutorial: Simple Linear Regressions
DataCamp
Python Tutorial: Autocorrelation
DataCamp
R Tutorial: The gapminder dataset
DataCamp
R Tutorial: The filter verb
DataCamp
R Tutorial: The arrange verb
DataCamp
R Tutorial: The mutate verb
DataCamp
R Tutorial: What is cluster analysis?
DataCamp
R Tutorial: Distance between two observations
DataCamp
R Tutorial: The importance of scale
DataCamp
R Tutorial: Measuring distance for categorical data
DataCamp
Python Tutorial: Plotting multiple graphs
DataCamp
Python Tutorial: Customizing axes
DataCamp
Python Tutorial: Legends, annotations, & styles
DataCamp
Python Tutorial: Introduction to iterators
DataCamp
Python Tutorial: Playing with iterators
DataCamp
Python Tutorial: Using iterators to load large files into memory
DataCamp
SQL Tutorial: Introduction to Relational Databases in SQL
DataCamp
SQL Tutorial: Tables: At the core of every database
DataCamp
SQL Tutorial: Update your database as the structure changes
DataCamp
Python Tutorial: Classification-Tree Learning
DataCamp
Python Tutorial: Decision-Tree for Classification
DataCamp
Python Tutorial: Decision-Tree for Regression
DataCamp
Python Tutorial: Census Subject Tables
DataCamp
Python Tutorial: Census Geography
DataCamp
Python Tutorial: Using the Census API
DataCamp
R Tutorial: A/B Testing in R
DataCamp
R Tutorial: Baseline Conversion Rates
DataCamp
R Tutorial: Designing an Experiment - Power Analysis
DataCamp
R Tutorial: Introduction to qualitative data
DataCamp
R Tutorial: Understanding your qualitative variables
DataCamp
R Tutorial: Making Better Plots
DataCamp
SQL Tutorial: OLTP and OLAP
DataCamp
SQL Tutorial: Storing data
DataCamp
SQL Tutorial: Database design
DataCamp
Python Tutorial: Introduction to spaCy
DataCamp
Python Tutorial: Statistical Models
DataCamp
Python Tutorial: Rule-based Matching
DataCamp
More on: Data Literacy
View skill →Related AI Lessons
🎓
Tutor Explanation
DeepCamp AI