Value at Risk (VAR) in Python under 25 lines of code [You MISS, You LOSE]馃敶 - YouTube

Channel: Financial Programming with Ritvik

[0]
Hello Hello mic test [馃憖Follow the Captions to Learn More馃憖]
[10]
hello guys i'm Ritvik Dashora and i'm back with a聽 new video and some new learnings if you're a smart聽聽
[15]
guy and interested to know how to calculate value聽 at risk aka var of a stock portfolio in python聽聽
[20]
then you are at the right place in this video聽 we will create a python model for value at Risk
[25]
which can be used for portfolio management or聽 trading purposes or for university projects聽聽
[30]
before we start building the var model in python聽 if you are new around here on this channel I turn聽聽
[36]
you into a successful financial programmer here i聽 upload videos related to trading bots some highly聽聽
[41]
valuable finance APIs implementation of ai in聽 finance etc etc so if this is something you are聽聽
[46]
interested in then smash on the subscribe button聽 and hit on the bell icon also I offer an amazing聽聽
[51]
gift to all my lovely subscribers you'll very soon聽 get to know about this in this video let's look at聽聽
[55]
the example of a bakery the bakery provides us聽 with baked goods in return we give them money聽聽
[60]
this money is their earning I'm not getting any聽 money from this YouTuber i just saw that there's聽聽
[65]
a new youtuber and i believe in growing together聽 then just growing alone the link of this video聽聽
[69]
is in the description box so let's build our var聽 model today we will talk about what is var value聽聽
[74]
at risk what is confidence interval then we'll聽 build a portfolio and calculate daily returns聽聽
[80]
through a python code we'll make a variance聽 covariance metrics we'll see how to calculate聽聽
[84]
the portfolio risk that is standard deviation聽 then we'll see how to calculate the portfolio聽聽
[88]
expected return in the end we'll construct the聽 normal distribution curve using the results and聽聽
[93]
then eventually we'll calculate var and confidence聽 interval so what is var and confidence interval聽聽
[98]
value at risk also known as var is a measure of聽 risk of loss for investments and this measure was聽聽
[104]
actually built in mid-90s and right now it is one聽 of the most important measure for risk management聽聽
[110]
in portfolio actually what it represents is that聽 for example, if we have a daily value at risk of聽聽
[115]
6.5 percent with a 95 percent confidence we mean聽 that there is a five percent confidence that our聽聽
[121]
portfolio will lose 6.5% or more in a day that's聽 why it is very important if we are interested in a聽聽
[127]
particular time period and we want to know the the聽 loss that it will make and what is the confidence聽聽
[132]
behind that loss then var is the measure for聽 you the flip side is that we have 95 percent聽聽
[137]
confidence that our portfolio will not lose聽 point six point five percent in a day this is an聽聽
[143]
important thing to note for portfolio management聽 now let's see what is parametric for the聽聽
[147]
parametric for is the model that we will going聽 to build in this video which is also known as聽聽
[152]
variance-covariance method will first identify the聽 mean the expected value and then we'll calculate聽聽
[157]
the standard deviation of the portfolio and then聽 using these two measures we will calculate the聽聽
[162]
var which is known as parametric var so i have聽 five percent confidence that my portfolio will聽聽
[167]
lose six point five percent or more in a day now聽 this or more is not defined this five percent can聽聽
[173]
mean that it will lose maybe fifty percent of the聽 portfolio so how to calculate the exact expected聽聽
[178]
loss if this trigger is hit for this there is聽 a different measure called conditional var if聽聽
[183]
you want me to cover conditional var or monte聽 carlo simulation to calculate value at risk in聽聽
[189]
python then just hit a like on this video if it聽 crosses 200 likes then I'll cover these topics聽聽
[193]
as well so what is confidence interval confidence聽 interval represents a range of values we predict聽聽
[197]
our true value lies in with some confidence okay聽 now so let's jump to the python code I'm using
[203]
yfinance to extract stock price data of different聽 companies there are other free APIs that are聽聽
[208]
available in the market I have covered some of聽 them such as 12 data alpha vintage iex cloud or聽聽
[214]
bloomberg in python if you are interested to know聽 more just click on this i button so let's start by聽聽
[218]
installing yfinance pip install yfinance let me聽 run this okay I've got it so let's import import聽聽
[224]
the libraries that i'm going to use in this聽 video are import yfinance as yf numpy as np聽聽
[231]
date time as dt and met plotlib dot py plot聽 as plt i'll also use a library called scipy.stats聽聽
[239]
import nom i just wrote some tickers here聽 apple facebook citibank disney ford microsoft聽聽
[246]
morgan stanley gamestop tesla and amazon and聽 these are 10 stocks and i just provided weights聽聽
[252]
of all these companies as equal-weighted portfolio聽 so all these 10 companies have 10% in our portfolio聽聽
[258]
it's an np dot array just it's not a list just聽 remember this so as for the things to cover聽聽
[264]
we'll have to build a portfolio first and聽 calculate the daily returns perfect so let's start聽聽
[268]
with the dates start is equal to dt dot date time聽 and then let's take 2019 1 1st of january 2019 and聽聽
[276]
the end is equal to dt.datetime.now today's date聽 now in order to download data what we do is df is聽聽
[283]
equal to yf i'm using this yfinance library dot聽 download and we just provide the ticker name here聽聽
[290]
for example if the ticker name is apple I'll do聽 it for all these stickers but yeah if it's just聽聽
[294]
one ticker so then we just provide the ticker name聽 start and then end if I run this cell you'll see聽聽
[301]
that the entire data frame is with you open high聽 low close adjusted close and volume I'm only
[307]
interested in adjusted close because i'll be聽 calculating returns on this column only so i'm聽聽
[313]
just interested in this so what i can do to get聽 the adjusted close price for all the stickers is聽聽
[318]
very easy i just need to do here is ticker which聽 represents this list and then in the end let's聽聽
[324]
do adj close if i run the cell I'll have to do聽 tickers here if i run this cell you'll see that聽聽
[330]
we have got adjusted close for all these companies聽 in just one data frame now in order to calculate
[335]
the returns it's fairly easy df dot percent change and then if I run this cell and check it i can you
[342]
can see that returns data frame is giving me聽 a daily return the percentage change return聽聽
[348]
of all these companies 10 companies and we have聽 the final data frame with you now our next task聽聽
[353]
is to calculate the variance covariance metrics聽 the risk the portfolio risk and the portfolio聽聽
[358]
expected return in order to calculate the variance聽 covariance metrics it's fairly easy what you need聽聽
[363]
to do here is cov matrix is equal to returns dot cov聽 simple and you can see that you have the variance聽聽
[370]
covariance matrix in front of you for the people聽 who don't know what is variance covariance matrix聽聽
[375]
is basically the diagonal represents the variance聽 for all these companies and all these other para聽聽
[382]
other numbers represents the the covariance聽 between these two companies so for example this is聽聽
[387]
the variance of apple stock price returns this is聽 the covariance between amazon and apple so you can聽聽
[392]
see that this value is equal to this value because聽 they have the same companies here and here of this聽聽
[399]
is the covariance of citibank and apple and so on聽 and the variance for citibank is this one because聽聽
[405]
you have citibank here and citibank here the聽 expected return is actually average returns in聽聽
[412]
the past so average returns is equal to returns聽 dot mean if i run this cell then you can see that聽聽
[418]
the average returns for all these 10 companies聽 is this one and we'll be assuming that these聽聽
[423]
average returns represents the expected return聽 for all these companies now let's see how many聽聽
[427]
observations are there how many rows are there for聽 each company that is the number of dates that are聽聽
[432]
available for each company's data for this we will聽 do count is equal to returns dot count if i run聽聽
[439]
this like this you can see that we have 569 rows聽 available for all the data so i'm only interested聽聽
[445]
in just like in this number so what i'll do聽 here is i'll just provide this so i have count聽聽
[451]
is equal to 569 rows now let's build the normal聽 distribution curve using all these results for聽聽
[456]
this we'll have to use the scipy dot stats library聽 in order to make a normal distribution curve we'll聽聽
[462]
have to find a mean and standard deviation聽 of portfolio not of these different companies聽聽
[468]
so to calculate mean and standard deviation of聽 portfolio what we'll have to do is we'll have to聽聽
[473]
use all these parameters and the weights that we聽 have given which is actually equal weight in this聽聽
[477]
example so let's see how to calculate it i found聽 a very interesting article on google the link is聽聽
[483]
in the description box and it states the formula聽 for expected portfolio return and the portfolio聽聽
[489]
variance this is m * w this * is actually聽 the matrix multiplication which is also known as聽聽
[495]
vector calculation or dot product m represents聽 the average returns matrix and w represents the聽聽
[501]
the weights array that we made which is actually聽 equal-weighted in our case this t represents the聽聽
[506]
transpose of the matrix and the covariance matrix聽 we have already built and then this is again聽聽
[512]
the weights the star is a matrix multiplication聽 so let's do it on our code so port mean is equal聽聽
[519]
to average returns at the rate weights now we use聽 at the rates to do the matrix multi multiplication聽聽
[526]
in python port std is equal to so weights this is聽 the transpose dot t at the rate cavariance matrix聽聽
[534]
at the rate weights now because it is standard聽 deviation it should be square root of the variance聽聽
[539]
perfect if I do portfolio mean it's two point聽 sorry point two nine percent of daily return this聽聽
[546]
is the expected daily return of our portfolio聽 and if I do it port std it is 2.27 percent聽聽
[553]
of our portfolio now let's use these parameters to聽 make a normal distribution curve in order to build聽聽
[558]
a normal distribution curve what we'll have to do聽 is we'll have to define an x-axis first which will聽聽
[564]
have evenly spaced numbers and on that axis聽 we'll make a normal distribution curve using the聽聽
[571]
scipy.stats python package for x-axis what we can聽 do is we will use np dot arange and you can see聽聽
[578]
that a range it returns evenly spaced values聽 within a given given interval which which is聽聽
[584]
actually the best for defining our x-axis so let's聽 make it from minus point zero five to plus point聽聽
[591]
zero five and the interval will be point zero zero聽 one this is the x-axis and if i run x you can see聽聽
[597]
that these are evenly spaced values again it's the聽 best for making the x-axis the normal distribution聽聽
[604]
will be norm dot pdf pdf represents probability聽 density function and then what i have to provide聽聽
[610]
here is x and then port mean and then聽 port standard deviation simple if i run聽聽
[615]
normal distribution here you can see that it looks聽 like a normal distribution because it starts with聽聽
[620]
a small value and then it goes to a higher value聽 and then in the end against a small value in order聽聽
[624]
to visualize it we'll have to draw it using matplotlib library so plt dot plot x comma norm聽聽
[630]
this and let me make color is equal to r plt dot聽 show perfect it's a it's a normal distribution聽聽
[635]
curve in front of you you can see in order to make聽 it look a bit better let me just increase it by聽聽
[640]
this one yeah now it's looking more like a normal聽 distribution curve now what we'll have to do here聽聽
[645]
is using this normal distribution curve we will聽 calculate the var which is the probability聽聽
[651]
of loss with five percent confidence of interval聽 so before I do that I have a huge announcement to聽聽
[655]
make i recently planned that once i reach 3000聽 subscribers i'll start having conversation with聽聽
[660]
industry experts and start sharing it on this聽 channel we will discuss about upcoming trends聽聽
[666]
jobs availability and the future prospects of聽 financial programming financial engineering and聽聽
[671]
quantitative finance if you're interested let's聽 cross 3000 subscribers as soon as possible and i'm聽聽
[676]
really excited to see a different dimension of our聽 youtube channel so now let's calculate the var now
[682]
considering the confidence level of confidence level of聽 0.05 var can be calculated like this norm dot ppf
[690]
which represents a percent point function inside聽 this i will have to provide confidence level the聽聽
[696]
port mean and port std if i run this i will see聽 that the var is equal to 3.4 percent loss so it聽聽
[705]
states that I have 95 confidence that my portfolio聽 will not lose more than 3.4 percent in one day now聽聽
[712]
if you are interested to see var or higher time聽 period such as 5 days or 10 days what we can do is聽聽
[719]
fairly easy so let me just write num days is聽 equal to say 5 and in that case what we can聽聽
[724]
do is var and then multiply by np dot sqrt and聽 then num days so it represents that in five days聽聽
[730]
my portfolio will not lose seven point seven聽 percent of its value now let's calculate the聽聽
[735]
confidence interval considering a confidence聽 level of say 95.5 percent why ninety five聽聽
[741]
point five four five percent because on this聽 value the value of z is equal to two if we see聽聽
[747]
the formula for confidence interval this is聽 basically the formula for confidence interval that聽聽
[751]
i'm going to use the value of z at ninety five聽 point five percent confidence is equal to two for聽聽
[756]
different confidence level you'll have to refer聽 to the z-table which can be available on google聽聽
[762]
or any other platform as well so in this case聽 I'll be using z is equal to two and then sigma聽聽
[766]
is the portfolio risk which is standard deviation聽 of portfolio and this n represents the count if聽聽
[771]
you remember the 569 number this is portfolio mean聽 so let's do it here the lower number would be port聽聽
[778]
mean and then minus if i go to the formula here聽 minus z multiplied by sigma divided by under roots聽聽
[784]
of n z is two multiplied by port std divided by聽 np dot sqrt and then count similarly for higher聽聽
[792]
port mean plus I'll just copy and paste this so聽 lower is this one and higher is this one so this聽聽
[798]
is the confidence interval of our portfolio聽 it means that we are 95.5 percent confident聽聽
[804]
that the daily return of our portfolio will be聽 between this and this now before telling you what聽聽
[808]
is the gift to all my subscribers if you have any聽 questions just drop it in the comment box i will聽聽
[812]
answer all of them if you don't have any questions聽 just comment that a great video or thank you so much聽聽
[817]
etc it really helps with the algorithm and also聽 don't forget to like this video for sure now the聽聽
[822]
gift now the gift to all my subscribers is that聽 this code will be saved in my google drive what聽聽
[827]
you can do is just subscribe to my youtube channel聽 and then click on access to my google drive button聽聽
[831]
follow some steps and then just provide some聽 basic details and I'll be using this email address聽聽
[835]
to provide a free access of my google drive聽 everything is free for use there are no copyright聽聽
[841]
issues if you found this video informative then聽 you can support me by becoming a patreon member聽聽
[847]
the link is in the description box and you can see聽 that there are various medals that are over there聽聽
[852]
for different medals you get different benefits such as article of the week my opinion etc聽聽
[858]
and if you click on see all six levels there are聽 other levels such as platinum legend and god medal聽聽
[864]
and things such as trading strategy of the month聽 premium fintech posts code of the week etc etc are聽聽
[870]
for different levels so just become a member of聽 any of these medals and support me thank you so聽聽
[875]
much for watching this video till the end click聽 here to subscribe to my youtube channel and over聽聽
[879]
there you can see that how i used TA-Lib library聽 to do technical analysis in python and over there聽聽
[885]
you can see how I created a bitcoin trading board聽 which generated some access returns over bitcoin聽聽
[890]
like this video share it with your friends and聽 I'll see you in the next video thank you so much