Quantitative Analysis, Risk Management, Modelling, Algo Trading, and Big Data Analysis

# Applied Portfolio VaR Decomposition. (1) Marginal and Component VaR.

Risk. The only ingredient of life that makes us growing and pushing outside our comfort zones. In finance, taking the risk is a risky business. Once your money have been invested, you need to keep your eyes on the ball that is rolling. Controlling the risk is the art and is the science: a quantitative approach that allows us to ease the pressure. With some proper tools we can manage our positions in the markets. No matter whether you invest in a long-term horizon or trade many times per day, your portfolio is a subject to the constantly changing levels of risk and asset volatility.

VaR. Value-at-Risk. The most hated and most adorable quantitative measure of risk. Your running security amongst the unpredictability of the floor. A drilling pain in the ass; a few sleepless nights you’ve been so familiarised with. The omnipresent and rarely confirmed assumptions of the assets returns to be normally distributed. Well, we all know the truth but, somehow, we love to settle for the analytical solutions allowing us to “see a less attractive girl” — more attractive.

In this post we will stay in the mystic circle of those assumptions as a starting point. Don’t blame me. This is what they teach us in the top-class textbooks on financial risk management and test our knowledge within FRM or CFA exams. You may pass the exam but do you really, I mean, really understand the effects of what you have just studied in real portfolio trading?

We kick off from a theory on VaR decomposition in the framework of an active $N$-asset portfolio when our initial capital of $C$ has been fully invested in the stock market (as an example). Next, we investigate the portfolio VaR and by computation of its marginal VaR we derive new positions in our portfolio that minimise the portfolio VaR.

The Analytical VaR for N-Asset Portfolio. The Beginning.

Let’s keep our theoretical considerations to the absolute but essential minimum. At the beginning you have $C$ dollars in hand. You decide to invest them all into $N$ assets (stocks, currencies, commodities, etc.). Great. Say, you pick up US equities and buy shares of $N=7$ stocks. The number of shares depends on stock price and each position size (in dollars) varies depending on your risk-return appetite. Therefore, the position size can be understood as a weighting factor, $w_i$, for $i=1,…,N$, such:
$$\sum_{i=1}^N w_i = 1 \ \ \mbox{or} \ \ 100\mbox{%}$$ or $d_i=w_iC$ in dollars and $\sum_i d_i=C$. Once the orders have been fulfilled, you are a proud holder of $N$-asset portfolio of stocks. Congratulations!

From now on, every day, when the markets close, you check a daily rate of return for individual assets, $r_{t,i} = P_{i,t}/P_{i,{t-1}}-1$ where by $P$ we denote the stock close price time-series. Your portfolio rate of return, day-to-day i.e. from $t$-1 to $t$, will be:
$$R_{p,t} = \sum_{i=1}^N w_ir_{i,t} = \boldsymbol{w}’\boldsymbol{r}$$ or alternatively:
$$R_{p,t} = \sum_{i=1}^N d_ir_{i,t} = \boldsymbol{d}’\boldsymbol{r}$$ what provides us with the updated portfolio value. Now, that differs from the portfolio expected return defined as:
$$\mu_P = E\left(\sum_{i=1}^{N} w_ir_i \right) = \sum_{i=1}^{N} w_i\mu_i = \boldsymbol{w}’\boldsymbol{\mu}$$ where the expected daily return of the $i$-th asset, $\mu_i$, needs to be estimated based on its historical returns (a return-series). This is the most fragile spot in the practical application of the Modern Portfolio Theory. If we estimate,
$$\mu_i = \sum_{t’={(t-1)}-T}^{{t-1}} r_{t’}/T$$ looking back at last $T$ trading days, it is obvious that we will derive different $\mu_i$’s for $T$=252 (1 year) and for $T$=1260 (5 years). That affects directly the computation of the portfolio covariance matrix thus, as we will see below, the (expected) portfolio volatility. Keep that crucial remark in mind!

The expected portfolio variance is:
$$\sigma_P^2 = \boldsymbol{w}’ \boldsymbol{M}_2 \boldsymbol{w}$$
where $\boldsymbol{M}_2$ is the covariance matrix $N\times N$ with the individual covariances of $c_{ij}=\mbox{cov}(\{r_i\},\{r_j\})$ between security $i$ and $j$ computed based on the return-series. Therefore,
$$\sigma_P^2 = [w_1,…,w_N] \left[ \begin{array}{cccc} c_{11} & c_{12} & … & c_{1N} \\ … & … & … & … \\ c_{N1} & c_{N2} & … & c_{NN} \end{array} \right] \left[ \begin{array}{cccc} w_{1} \\ … \\ w_{N} \end{array} \right]$$ what can be expressed in the terms of the dollar exposure as:
$$\sigma_P^2C^2 = \boldsymbol{d}’ \boldsymbol{M}_2 \boldsymbol{d} \ .$$ In order to move from the portfolio variance to the portfolio VaR we need to know the distribution of the portfolio returns. And we assume it to be normal (delta-normal model). Given that, the portfolio VaR at the 95% confidence level ($\alpha=1.65$) is:
$$\mbox{VaR}_P = 1.65 \sigma_P C = 1.65\left(\boldsymbol{d}’ \boldsymbol{M}_2 \boldsymbol{d} \right)^{1/2}$$ what can be understood as diversified VaR since we use our portfolio to reduce the overall risk of the investment. On the other hand, the 95% individual VaR describing individual risk of each asset in the portfolio is:
$$\mbox{VaR}_i = 1.65 |\sigma_i d_i|$$ where $\sigma_i$ represents the asset volatility over past period of $T$.

It is extremely difficult to obtain a portfolio with a perfect correlation (unity) among all its components. In such a case, we would talk about undiversified VaR possible to be computed as a sum of $\mbox{VaR}_i$ when, in addition as a required condition, there is no short position held in our portfolio. Reporting the risk for a portfolio currently alive is often conducted by the risk managers by providing a quotation of both diversified and undiversified VaR.

Now, imagine that we add one unit of an $i$-th asset to our portfolio and we aim at understanding the impact of this action on the portfolio VaR. In this case we talk about a marginal contribution to risk, possible to be derived through the differentiation of the portfolio variance with respect to $w_i$:
$$\frac{\mbox{d}\sigma_P}{\mbox{d}w_i} = \frac { \left[ \sum_{i=1}^{N} w_i^2\sigma_i^2 + \sum_{i=1}^N \sum_{j=1, j\ne i}^{N} w_iw_jc_{ij} \right]^{1/2} } { \mbox{d}w_i }$$
$$= \frac{1}{2} \left[ 2w_i\sigma_i^2 + 2 \sum_{j=1, j\ne 1}^{N} w_jc_{ij} \right] \times \\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \left[ \sum_{i=1}^{N} w_i^2\sigma_i^2 + \sum_{i=1}^N \sum_{j=1, j\ne i}^{N} w_iw_jc_{ij} \right]^{-1/2}$$
$$= \frac{w_i^2\sigma_i^2 + \sum_{j=1, j\ne 1}^{N} w_j c_{ij} } {\sigma_P} = \frac{c_{iP}}{\sigma_P}$$ where, again, $c_{ij}$ denotes the covariance between any $i$-th and $j$-th asset and $c_{iP}$ between $i$-th component and portfolio. That allows us to define the marginal VaR for $i$-th asset in the portfolio in the following way:
$$\Delta\mbox{VaR}_i = \frac{\mbox{dVaR}_P}{\mbox{d}d_i} = \frac{\mbox{dVaR}_P}{\mbox{d}w_iC} = \frac{\mbox{d}(\alpha\sigma_P C)}{\mbox{d}w_iC} = \alpha\frac{C}{C} \frac{\mbox{d}\sigma_P}{\mbox{d}w_i} = \alpha \frac{c_{iP}}{\sigma_P}$$ that has a close relation to the systematic risk of $i$-th asset as confronted with the portfolio itself, described by:
$$\beta_i = \frac{c_{iP}}{\sigma_P^2}$$ therefore
$$\Delta\mbox{VaR}_i = \alpha \sigma_P \beta_i = \beta_i \frac{ \mbox{VaR}_P } {C}$$ The best and most practical interpretation of the marginal VaR calculated for all positions in the portfolio would be: the higher $\Delta\mbox{VaR}_i$ the corresponding exposure of the $i$-th component should be reduced to lower the overall portfolio VaR. Simple as that. Hold on, we will see that at work in the calculations a little bit later.

Since the portfolio volatility is a highly nonlinear function of its components, a simplistic computation of individual VaRs and adding the up all together injects the error into portfolio risk estimation. However, with a help of the marginal VaR we gain a tool to capture the fireflies amongst the darkness of the night.

We define the component VaR as:
$$\mbox{cVaR}_i = \Delta\mbox{VaR}_i d_i = \Delta\mbox{VaR}_i w_i C = \beta_i \frac{ \mbox{VaR}_P w_i C } {C} = \beta_i w_i \mbox{VaR}_P$$ utilising the observation that:
$$\sigma_P = \sum_{i=1}^{N} w_i c_{iP} = \sum_{i=1}^{N} w_i \beta_i \sigma_P = \sigma_P \sum_{i=1}^{N} w_i \beta_i = \sigma_P$$ what very nicely leads us to:
$$\sum_{i=1}^{N} \mbox{cVaR}_i = \mbox{VaR}_P \sum_{i=1}^{N} w_i \beta_i = \mbox{VaR}_P \ .$$ Having that, we get the percent contribution of the $i$-th asset to the portfolio VaR as:
$$i = \frac{ \mbox{cVaR}_i } { \mbox{VaR}_P } = w_i \beta_i$$ It is possible to calculate the required changes in the positions sizes based on our VaR analysis. We obtain it by re-evaluation of the portfolio marginal VaRs meeting now the following condition:
$$\Delta\mbox{VaR}_i = \beta_i \frac{ \mbox{VaR}_P } { C } = \ \mbox{constant .}$$ a subject of finding a solution for a “Risk-Minimising Position” problem. All right. The end of a lecture. Time for coding!

Case Study

Do You like sex? I do! So, let’s do it in Matlab this time! First, we pick up randomly seven stocks among US equites (for the simplicity of this example), and their tickers are given in the portfolio.lst text file as follows:

AAPL DIS IBM JNJ KO NKE TXN

and next we download their 3 years of historical data from Quandl.com as the data provider:

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 % Applied Portfolio VaR Decomposition. (1) Marginal and Component VaR. % % (c) 2015 QuantAtRisk.com, by Pawel Lachowicz   clear all; close all; clc; format short   % Read the list of the portfolio components fileID = fopen('portfolio.lst'); tmp = textscan(fileID, '%s'); fclose(fileID); pc=tmp{1}; % a list as a cell array   % fetch stock data for last 3 years since: t0=735976; % 12-Jan-2015 date2=datestr(t0,'yyyy-mm-dd'); % from date1=datestr(t0-3*365,'yyyy-mm-dd'); % to   % create an empty array for storing stock data stockd={}; for i=1:length(pc) % scan the tickers and fetch the data from Quandl.com quandlc=['WIKI/',pc{i}]; fprintf('%4.0f %s\n',i,quandlc); % fetch the data of the stock from Quandl % using recommanded Quandl's command and % saving them directly into Matlab's FTS object (fts) fts=0; [fts,headers]=Quandl.get(quandlc,'type','fints', ... 'authcode','YourQuandlCode',... 'start_date',date1,'end_date',date2); stockd{i}=fts; % entire FTS object in an array's cell end   % limit data to 3 years of trading days, select the adjusted % close price time-series and calculate return-series rs=[]; for i=1:length(pc) cp=fts2mat(stockd{i}.Adj_Close,0); rv=cp(2:end,1)./cp(1:end-1,1)-1; rs=[rs rv(end-(3*5*4*12):end)]; end rs(isnan(rs))=0.0;

The covariance matrix, $\boldsymbol{M}_2$, computed based on 7 return-series is:

44 45 % covariance matrix M2=cov(rs);

Let’s now assume some random dollar exposure, i.e. position size for each asset,

47 48 49 50 51 52 53 54 55 56 57 % exposure per position d=[ 55621.00; ... 101017.00; ... 23409.00; ... 1320814.00; ... 131145.00; ... 321124.00; ... 1046867.00]   % invested capital of C C=sum(d)

returning our total exposure of $C=\$$2,999,997 in the stock market which is based on the number of shares purchased and/or our risk-return appetite (in Part II of this series, we will witness how that works in a simulated trading). We turn a long theory on the VaR decomposition into numbers just within a few lines of code, namely: 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 % the portfolio volatility vol_p=sqrt(d'*M2*d); % diversified portfolio VaR VaR_P=1.65*vol_p; % volatility of assets (based on daily returns) v=sqrt(diag(cov(rs))); % individual and undiversified portfolio VaR VaRi=1.65*abs(v.*d); uVaR_P=sum(VaRi); % the portfolio betas beta=C*(M2*d)/vol_p^2; % the portfolio marginal VaR DVaR=1.65*(M2*d)/vol_p; % the component VaR [percent] cVaR=100*DVaR.*d/VaR_P; % initial positions of assets in portfolio [percent] orgpos=100*d/C The last column vector provides us with an information on the original (currently held) rate of exposure of our invested capital in a function of the asset number in portfolio: orgpos = 1.85 3.37 0.78 44.03 4.37 10.70 34.90 Before we generate our very first risk report, let’s develop a short code that would allow us to find a solution for “Risk-Minimising Position” problem. Again, we want to find new position sizes (different from orgpos) at the lowest possible level of the portfolio risk. We construct intelligently a dedicated function that does the job for us: % Finding a solution for the "Risk-Minimasing Position" problem % based on portfolio VaR % (c) 2015 QuantAtRisk, by Pawel Lachowicz function [best_x,best_dVaR,best_VaRp,best_volp]=rmp(M2,d,VaR_p) c=sum(d); N=length(d); best_VaRp=VaR_p; for i=1:100 % an arbitrary number (recommended >50) k=0; while(k~=1) d=random('uniform',0,1,N,1); d=d/sum(d)*c; vol_p=sqrt(d'*M2*d); % diversified VaR (portfolio) VaRp=1.65*vol_p; dVaR=1.65*(M2*d)/vol_p; test=fix(dVaR*100); % set precision here m=fix(mean(test)); t=(test==m); k=sum(t)/N; if(VaRp<best_VaRp) best_x=d; best_dVaR=dVaR; best_VaRp=VaRp; best_volp=vol_p; end end end end We feed it with three input parameters, namely, the covariance matrix of \boldsymbol{M}_2, the current dollar exposure per asset of \boldsymbol{d}, and the current portfolio VaR. Inside we generate randomly a new dollar exposure column vector, next re-calculate the portfolio VaR and marginal VaR until,$$ \Delta\mbox{VaR}_i = \beta_i \frac{ \mbox{VaR}_P } { C } = \ \mbox{constant} $$condition is met. We need to be sure that a new portfolio VaR is lower than the original one and somehow lowest among a large number of random possibilities. That is why we repeat that step 100 times. In this point, as a technical remark, I would suggest to use more than 50 iterations and to experiment with a precision that is required to find marginal VaRs (or \beta’s) to be (nearly) the same. The greater both golden numbers are the longer time of waiting for the final solution. It is also that apex of the day in daily bank’s portfolio evaluation process that assesses the bank’s market risk and global exposure. A risk manager knows how long it takes to find new risk-minimaised positions and how fast C/C++/GPU solutions need to be implemented to cut the time of those computations. Here, with our Matlab function of rmp, we can feel the pain of this game. Eventually, we finalise our computations: 84 85 86 [nd,nDVaR,nVaR_P,nvol_P]=rmp(M2,d,VaR_P); redVaR=100*(nVaR_P-VaR_P)/VaR_P; newpos=100*nd/C; followed by a nicely formatted report: 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 fprintf('\n============================================\n'); fprintf(' Portfolio Risk Report as of %s\n',datestr(t0)); fprintf('============================================\n\n'); fprintf('1-day VaR estimation at %1.0f%% confidence level\n\n',95.0) fprintf('Number of assets:\t\t %1.0f \n',length(d)) fprintf('Current exposure:\t\t %1s\n',bankformat(C)); fprintf('Portfolio VaR (undiversified):\t %1s\n',bankformat(uVaR_P)); fprintf('Portfolio VaR (diversified):\t %1s\n',bankformat(VaR_P)); fprintf('Component VaR [individual VaR]\n'); for i=1:length(d) fprintf(' %s\t%6.2f%% %-10s\t[%-10s]\n',pc{i},cVaR(i), ... bankformat(cVaRd(i)),bankformat(VaRi(i))); end fprintf('\nRisk-Minimising Position scenario\n'); fprintf('--------------------------------------------------------------'); fprintf('\n\t\t Original Marginal New Marginal\n'); fprintf('\t\t position VaR position VaR\n'); for i=1:length(d) fprintf('\t %-4s\t %6.2f%% %1.5f\t %6.2f%% %1.2f\n', ... pc{i},orgpos(i), ... DVaR(i),newpos(i),nDVaR(i)) end fprintf('div VaR\t\t %1s\t\t %1s\n',bankformat(VaR_P), ... bankformat(nVaR_P)); fprintf('\t\t\t\t\t%10.2f%%\n',redVaR); fprintf('ann Vol\t\t%10.2f%%\t\t%10.2f%%\n', ... sqrt(252)*vol_P/1e6*1e2,sqrt(252)*nvol_P/1e6*1e2); fprintf('--------------------------------------------------------------'); fprintf('\n\n'); where bankformat function you can find here. As a portfolio risk manager you are interested in numbers, numbers, and numbers that, in fact, reveal a lot. It is of paramount importance to analyse the portfolio risk report with attention before taking any further steps or decisions:  ============================================ Portfolio Risk Report as of 12-Jan-2015 ============================================ 1-day VaR estimation at 95% confidence level Number of assets: 7 Current exposure: 2,999,997.00 Portfolio VaR (undiversified): 54,271.26 Portfolio VaR (diversified): 33,027.94 Component VaR [individual VaR] AAPL 0.61% 202.99 [1,564.29 ] DIS 1.71% 564.13 [1,885.84 ] IBM 0.26% 84.43 [429.01 ] JNJ 30.99% 10,235.65 [17,647.63 ] KO 1.19% 392.02 [2,044.05 ] NKE 9.10% 3,006.55 [7,402.58 ] TXN 56.14% 18,542.15 [23,297.83 ] Risk-Minimising Position scenario -------------------------------------------------------------- Original Marginal New Marginal position VaR position VaR AAPL 1.85% 0.00365 6.02% 0.01 DIS 3.37% 0.00558 1.69% 0.01 IBM 0.78% 0.00361 10.79% 0.01 JNJ 44.03% 0.00775 37.47% 0.01 KO 4.37% 0.00299 27.36% 0.01 NKE 10.70% 0.00936 8.13% 0.01 TXN 34.90% 0.01771 8.53% 0.01 div VaR 33,027.94 26,198.39 -20.68% ann Vol 31.78% 25.21% -------------------------------------------------------------- From the risk report we can spot the difference of \$$21,243.32 between the undiversified and diversified portfolio VaR and the largest contribution of Texas Instruments Incorporated stock (TXN) to the overall portfolio VaR though it is Johnson & Johnson stock (JNJ) that occupies the largest dollar position in our portfolio. The original marginal VaR is the largest for TXN, NKE, and JNJ. Therefore, in order to minimise portfolio VaR, we should cut them and/or reduce their positions. On the other hand, the exposure should be increased in case of KO, IBM, AAPL, and DIS which display the lowest marginal VaR. Both suggestions find the solution in a form of derived new holdings that would reduce the portfolio VaR by$-\$20.68% decreasing concurrently the annualised portfolio volatility by 6.57%.

Indeed. Risk is like sex. The more the merrier! Unless, you are a risk manager and you calculate your “positions”.

• Charles G

What is missing in this code if a definition for CVaRd This should be

cVaRd=DVaR.*d;

• Charles G

What is output from this function [nd,nDVaR,nVaR_P,nvol_P]=rmp(M2,d,VaR_P); in line 84 above? For example what is ‘nd’? Is this the USD value of holdings?

• Charles G

I like this script. I want to leverage it for my currency portfolio.I am relatively new to Matlab but I have followed the majority of the script. Where does the variable ‘CVaRd’ come from in the risk report script, line 99.

I am running the rmp function too. Its not ending any time soon. Is this the point? If so I am not able to run all risk reports, i.e that which uses the minimum risk portfolio. Any advise.

I cant seem to get the Quand api working, but I only need to see the the format of the inputs to this script.. for example what is ‘pc’? A single column cell array of stock names?

• rahul modak

Hi..
You have used variance co variance approach which can be called a little less analytical.. I think delta-gamma approximation is more analytical though complicated. That’s what we use at our fund.
So instead of assuming linear relation between risk factors and portfolio value use quadratic relation. Of course we need first and second order partial derivatives of portfolio value w.r.t. risk factors.
The main advantage would be to use delta gamma to speed up Monte Carlo by importance sampling.
Also see Glasserman Hidelberger and Shahbuddin “Importance sampling and stratification for VaR” ..