Python Tutorial: Measuring risk of a portfolio

DataCamp · Beginner ·🔢 Mathematical Foundations ·6y ago

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 SQL Server Tutorial: Date manipulation
SQL Server Tutorial: Date manipulation
DataCamp
2 R Tutorial: Intermediate Interactive Data Visualization with plotly in R
R Tutorial: Intermediate Interactive Data Visualization with plotly in R
DataCamp
3 R Tutorial: Adding aesthetics to represent a variable
R Tutorial: Adding aesthetics to represent a variable
DataCamp
4 R Tutorial: Moving Beyond Simple Interactivity
R Tutorial: Moving Beyond Simple Interactivity
DataCamp
5 Python Tutorial: Why use ML for marketing? Strategies and use cases
Python Tutorial: Why use ML for marketing? Strategies and use cases
DataCamp
6 Python Tutorial: Preparation for modeling
Python Tutorial: Preparation for modeling
DataCamp
7 Python Tutorial: Machine Learning modeling steps
Python Tutorial: Machine Learning modeling steps
DataCamp
8 R Tutorial: The prior model
R Tutorial: The prior model
DataCamp
9 R Tutorial: Data & the likelihood
R Tutorial: Data & the likelihood
DataCamp
10 R Tutorial: The posterior model
R Tutorial: The posterior model
DataCamp
11 R Tutorial: An Introduction to plotly
R Tutorial: An Introduction to plotly
DataCamp
12 R Tutorial: Plotting a single variable
R Tutorial: Plotting a single variable
DataCamp
13 R Tutorial: Bivariate graphics
R Tutorial: Bivariate graphics
DataCamp
14 Python Tutorial: Customer Segmentation in Python
Python Tutorial: Customer Segmentation in Python
DataCamp
15 Python Tutorial: Time cohorts
Python Tutorial: Time cohorts
DataCamp
16 Python Tutorial: Calculate cohort metrics
Python Tutorial: Calculate cohort metrics
DataCamp
17 Python Tutorial: Cohort analysis visualization
Python Tutorial: Cohort analysis visualization
DataCamp
18 R Tutorial: Building Dashboards with flexdashboard
R Tutorial: Building Dashboards with flexdashboard
DataCamp
19 R Tutorial: Anatomy of a flexdashboard
R Tutorial: Anatomy of a flexdashboard
DataCamp
20 R Tutorial: Layout basics
R Tutorial: Layout basics
DataCamp
21 R Tutorial: Advanced layouts
R Tutorial: Advanced layouts
DataCamp
22 Python Tutorial: Time Series Analysis in Python
Python Tutorial: Time Series Analysis in Python
DataCamp
23 Python Tutorial: Correlation of Two Time Series
Python Tutorial: Correlation of Two Time Series
DataCamp
24 Python Tutorial: Simple Linear Regressions
Python Tutorial: Simple Linear Regressions
DataCamp
25 Python Tutorial: Autocorrelation
Python Tutorial: Autocorrelation
DataCamp
26 R Tutorial: The gapminder dataset
R Tutorial: The gapminder dataset
DataCamp
27 R Tutorial: The filter verb
R Tutorial: The filter verb
DataCamp
28 R Tutorial: The arrange verb
R Tutorial: The arrange verb
DataCamp
29 R Tutorial: The mutate verb
R Tutorial: The mutate verb
DataCamp
30 R Tutorial: What is cluster analysis?
R Tutorial: What is cluster analysis?
DataCamp
31 R Tutorial: Distance between two observations
R Tutorial: Distance between two observations
DataCamp
32 R Tutorial: The importance of scale
R Tutorial: The importance of scale
DataCamp
33 R Tutorial: Measuring distance for categorical data
R Tutorial: Measuring distance for categorical data
DataCamp
34 Python Tutorial: Plotting multiple graphs
Python Tutorial: Plotting multiple graphs
DataCamp
35 Python Tutorial: Customizing axes
Python Tutorial: Customizing axes
DataCamp
36 Python Tutorial: Legends, annotations, & styles
Python Tutorial: Legends, annotations, & styles
DataCamp
37 Python Tutorial: Introduction to iterators
Python Tutorial: Introduction to iterators
DataCamp
38 Python Tutorial: Playing with iterators
Python Tutorial: Playing with iterators
DataCamp
39 Python Tutorial: Using iterators to load large files into memory
Python Tutorial: Using iterators to load large files into memory
DataCamp
40 SQL Tutorial: Introduction to Relational Databases in SQL
SQL Tutorial: Introduction to Relational Databases in SQL
DataCamp
41 SQL Tutorial: Tables: At the core of every database
SQL Tutorial: Tables: At the core of every database
DataCamp
42 SQL Tutorial: Update your database as the structure changes
SQL Tutorial: Update your database as the structure changes
DataCamp
43 Python Tutorial: Classification-Tree Learning
Python Tutorial: Classification-Tree Learning
DataCamp
44 Python Tutorial: Decision-Tree for Classification
Python Tutorial: Decision-Tree for Classification
DataCamp
45 Python Tutorial: Decision-Tree for Regression
Python Tutorial: Decision-Tree for Regression
DataCamp
46 Python Tutorial: Census Subject Tables
Python Tutorial: Census Subject Tables
DataCamp
47 Python Tutorial: Census Geography
Python Tutorial: Census Geography
DataCamp
48 Python Tutorial: Using the Census API
Python Tutorial: Using the Census API
DataCamp
49 R Tutorial: A/B Testing in R
R Tutorial: A/B Testing in R
DataCamp
50 R Tutorial: Baseline Conversion Rates
R Tutorial: Baseline Conversion Rates
DataCamp
51 R Tutorial: Designing an Experiment - Power Analysis
R Tutorial: Designing an Experiment - Power Analysis
DataCamp
52 R Tutorial: Introduction to qualitative data
R Tutorial: Introduction to qualitative data
DataCamp
53 R Tutorial: Understanding your qualitative variables
R Tutorial: Understanding your qualitative variables
DataCamp
54 R Tutorial: Making Better Plots
R Tutorial: Making Better Plots
DataCamp
55 SQL Tutorial: OLTP and OLAP
SQL Tutorial: OLTP and OLAP
DataCamp
56 SQL Tutorial: Storing data
SQL Tutorial: Storing data
DataCamp
57 SQL Tutorial: Database design
SQL Tutorial: Database design
DataCamp
58 Python Tutorial: Introduction to spaCy
Python Tutorial: Introduction to spaCy
DataCamp
59 Python Tutorial: Statistical Models
Python Tutorial: Statistical Models
DataCamp
60 Python Tutorial: Rule-based Matching
Python Tutorial: Rule-based Matching
DataCamp

This video tutorial teaches how to measure portfolio risk using Python, including calculating variance and standard deviation, and implementing matrix notation for covariance matrices. By the end of this lesson, you will be able to apply these concepts to your own portfolio analysis. The tutorial uses DataCamp's Introduction to Portfolio Analysis in Python course as a reference.

Key Takeaways
  1. Calculate daily returns using the percentage change function
  2. Calculate the covariance matrix
  3. Analyze volatility by multiplying with 250
  4. Create a simple equal weight portfolio
  5. Apply the formula for portfolio variance using matrix notation
  6. Calculate the standard deviation by taking the square root of the variance
💡 The portfolio variance is not simply the sum of all variances of the underlying stocks, but also depends on the correlation between the assets.

Related AI Lessons

Up next
How to Open IWB Files (SMART Notebook)
File Extension Geeks
Watch →