# 【Quant(16)】Portfolio VaR

Apply Variance-Covariance Method

# Highlights

• Difficulty：★★☆☆☆
• Portfolio VaR calculation & analysis
• Reminder: We would apply Python to calculate VaR by variance-covariance method. Therefore, it would be better for you to understand fundamentals of portfolio and Statistics.

# Preface

Value at risk, VaR, means the maximum loss of a portfolio by determined confidence level and data of specific period.

The procedure of calculation is as follow:

1. Daily Earnings at Risk
2. Correlation coefficient between stocks
3. VaR of portfolio

During computing, we should notice every parameter setting and distribution of stock return so as to reflect market’s volatility on the numbers. Subsequently, we would carefully implement the process and illustrate the defect of variance-covariance method.

1. Daily Earning at Risk, DEAR：The potential loss of a portfolio’s value in single day.

2. Relative VaR：The VaR compared to average return of portfolio.

(|-α| * σ) * portfolio value

3. Absolute VaR：The VaR compared to 0.

(|-α| * σ — mean) * portfolio value

Above α is the critical value of normal distribution. We would apply the the most restrict standard, 99% confidence level and Z-value equal to 2.33 to compute.

# Editing Environment and Modules Required

MacOS & Jupyter Notebook

`# Basicimport numpy as npimport pandas as pd# Graphimport matplotlib.pyplot as plt%matplotlib inlineimport seaborn as snssns.set()# TEJ APIimport tejapitejapi.ApiConfig.api_key = 'Your Key'tejapi.ApiConfig.ignoretz = True`

# Database

Security Transaction Data Table: Listed securities with adjusted and unadjusted price and index. Code is ‘TWN/EWPRCD’.

Security Return Data Table: Listed securities with different period basis return. Code is ‘TWN/EWPRCD2’.

# Data Selection & Pre-processing

Step 1. Stock Price

The portfolio would consist of traditional , high-tech, finance and shipping corporation. We would calculate VaR and display the distribution of every stock. By combining above parts, we would make you understand the pro-and-con of Variance-Covariance VaR.

`# Eclat Textile, TSMC, Cathay Financial Holdings and EVERGREENticker = ['1476', '2330', '2882', '2603']# Security Transaction Data Table-Adjusted Pricedf = tejapi.get('TWN/EWPRCD',                 coid = ticker,                mdate = {'gte':'20200101', 'lte':'20220225'},                opts = {'columns': ['coid', 'mdate', 'close_adj']},                chinese_column_name = True,                paginate = True)df = df.set_index('日期')`

Step 2. Transpose Price Data

`data = {}for i in ticker:    p = df[df['證券代碼'] == i]    p = p['收盤價(元)']    data.setdefault(i, p)data = pd.concat(data, axis = 1)`

Step 3. Daily Return

Apply Security Return Data Table to ensure the source quality. Pre-processing of return data is the same as that of price.

`# Security Return Data Table-Daily Returnret = tejapi.get('TWN/EWPRCD2',                   coid = ticker,                  mdate = {'gte':'20200101', 'lte':'20220225'},                  opts = {'columns': ['coid', 'mdate', 'roia']},                  chinese_column_name = True,                  paginate = True)ret = ret.set_index('日期')data2 = {}for i in ticker:    r = ret[ret['證券碼'] == i]    r = r['日報酬率(%)']    data2.setdefault(i, r)data2 = pd.concat(data2, axis = 1)data2 = data2 * 0.01 ＃ Transform return data to 2-decimal basis`

# Daily Return at Risk, DEAR

Step 1. Declare Empty Lists

`value = data.iloc[-1] * 1000Mean = []STD = []MAX = []Min = []abs_var = []re_var = []`

Firstly, we would calculate value of stocks in portfolio, assuming hold at least 1,000 share, which is the base unit in TAIEX. Subsequently, declare empty lists.

Step 2. Calculate DEAR, one-day VaR

`for i in ticker:    v = data2[i].std()              # Standard Error    mean = data2[i].mean()          # Mean     maximum = data2[i].max()        # Maximum    minimum = data2[i].min()        # Minimum        # Calculate 99% Absolute VaR    var_99_ab = (abs(-2.33)*v - mean) * value[i]       # Calculate 99% Relative VaR    var_99_re = (abs(-2.33)*v) * value[i]                # Append those values in lists    Mean.append(mean)    STD.append(v)    MAX.append(maximum)    Min.append(minimum)    abs_var.append(var_99_ab)    re_var.append(var_99_re)`

In the loop, we firstly calculate std, mean, maximum and minimum. Secondly, compute absolute and relative VaR. Lastly, return values to empty lists.

We apply abs() during calculation of VaR, which is for the remind of that VaR concerns the downside, namely the negative, so -2.33 is adequate. However, using positive number is the convention of presenting VaR; therefore, convert -2.33 to positive by abs().

Step 3. Construct new Table

`dear = pd.DataFrame({'Mean': Mean, 'STD': STD, 'Maximum': MAX, 'Minimum': Min, '99%絕對VaR': abs_var, '99%相對VaR': re_var},index = ticker)`

# Correlation Coefficient

`rho = data2.corr() # data2 is the transposed one of return data`

Instead of price data, we apply return data to get the correlation coefficient among stocks. By doing so, we would avoid Spurious Regression and compute correct coefficient.

# Portfolio VaR

Step 1. Concatenate Tables

`dear = dear.drop(columns = ['Mean', 'STD', 'Maximum', 'Minimum'])# concatenate dear and rhoportfolio = pd.concat([dear, rho,], axis = 1) portfolio[['99%絕對VaR', '99%相對VaR']] = portfolio[['99%絕對VaR', '99%相對VaR']]`

Step 2. Calculate VaR

part1 is the proportion of VaR of stocks itself in portfolio. As for part2, it is the VaR with the adjustment of correlation coefficient among different stocks.

`# Absolute VaRpart1 = sum(portfolio['99%絕對VaR']**2)            part2 = 2*portfolio.iat[0,3] * portfolio.iat[0,0] * portfolio.iat[1,0] \+ 2*portfolio.iat[0,4] * portfolio.iat[0,0] * portfolio.iat[2,0] \+ 2*portfolio.iat[0,5] * portfolio.iat[0,0] * portfolio.iat[3,0] \+ 2*portfolio.iat[1,4] * portfolio.iat[1,0] * portfolio.iat[2,0] \+ 2*portfolio.iat[1,5] * portfolio.iat[1,0] * portfolio.iat[3,0] \+ 2*portfolio.iat[2,5] * portfolio.iat[2,0] * portfolio.iat[3,0]`

Absolute VaR at 99% confidence level is 50647.78.

`# Relative VaRpart1 = sum(portfolio['99%相對VaR']**2)            part2 = 2*portfolio.iat[0,3] * portfolio.iat[0,1] * portfolio.iat[1,1] \+ 2*portfolio.iat[0,4] * portfolio.iat[0,1] * portfolio.iat[2,1] \+ 2*portfolio.iat[0,5] * portfolio.iat[0,1] * portfolio.iat[3,1] \+ 2*portfolio.iat[1,4] * portfolio.iat[1,1] * portfolio.iat[2,1] \+ 2*portfolio.iat[1,5] * portfolio.iat[1,1] * portfolio.iat[3,1] \+ 2*portfolio.iat[2,5] * portfolio.iat[2,1] * portfolio.iat[3,1]`

Relative VaR at 99% confidence level is 52205.86.

According to above calculation, we conclude that maximum loss of the portfolio in one day would not exceed 52 thousands at 99 percent chance. However, market always fluctuates. Hence, keeping the calculation of VaR regularly would make our judgement more accurately.

# Defects of Variance-Covariance Method

1. Unable to measure VaR of non-linear asset, like option. Since the structure of correlation coefficient has assumed that there is a linear relation among data, this method is not suitable for non-linear asset.
2. Ignore fat-tail. we use critical value of normal distribution to calculate DEAR, which might make us underestimate VaR due to the fat-tail problem of security asset.

We would display distributions of stocks so as to check severity of fat-tail.

`fig, ax =plt.subplots(figsize = (18, 12), nrows = 2, ncols = 2)data2['1476'].plot.hist(ax=ax, bins = 100,range=(data2['1476'].min(), data2['1476'].max()),  label = '儒鴻')ax.legend(loc = 2, fontsize = 30)data2['2330'].plot.hist(ax=ax, bins = 100,range=(data2['2330'].min(), data2['2330'].max()),  label = '台積電')ax.legend(loc = 2, fontsize = 30)data2['2882'].plot.hist(ax=ax, bins = 100,range=(data2['2882'].min(), data2['2882'].max()),  label = '國泰金')ax.legend(loc = 2, fontsize = 30)data2['2603'].plot.hist(ax=ax, bins = 100,range=(data2['2603'].min(), data2['2603'].max()),  label = '長榮')ax.legend(loc = 2, fontsize = 30)plt.tight_layout()`

Based on above charts, it is clear that EVERGREEN’s fat-tail is the most apparent. TSMC and Eclat Textile have fat-tail but not that dramatic. As for Cathay Financial Holdings, there is almost no fat-tail.

# Conclusion

With the process of calculation and analysis in this article, believe you would understand the procedure of Variance-Covariance Method. Firstly, calculate DEAR. Subsequently, get the correlation coefficient. Lastly, compute VaR of the whole portfolio. It is for sure that there is some disadvantages of this method and you can understand that fat-tail problem exists in these stocks. As a result, if you are curious about the solution for fat-tail, pleaser keep tracking this platform. We, later, will post new article to demonstate. In the end, welcome to purchase the plans offered in TEJ E Shop to conduct VaR calculation for your own portfolio.

# Source Code

You could give us encouragement by …
We will share financial database applications every week.
If you think today’s article is good, you can click on the
applause icon once.
If you think it is awesome, you can hold the
applause icon until 50 times. 