Original link:tecdat.cn/?p=22788
Original source:Tuo End number according to the tribe public number
Python calculates the risk measures for obtaining a multi-asset portfolio.
A key concept
- As prices change, so does the market value of an investment manager’s holdings. The latter is known as market risk, and one of the most popular ways to measure it is defined as value at risk. Risk itself is seen as the difference between actual and expected returns, which may be different. If they are equal, the investment is said to be risk-free. At the same time, it cannot have default risk, nor can it have reinvestment risk. Note that expected returns are not what investors think they will get, but rather reflect the average of all possible outcomes across all economic scenarios.
- Value at risk (VaR) tells you how much money you can lose at a predetermined confidence level over a given period of time. The typical confidence levels are 95% and 99%, meaning that the analyst has 95% or 99% confidence that the loss will not exceed this figure, i.e., a 5% (or 1%) VaR reflects a 5% (or 1%) worst-case future best return. Value-at-risk is a state-of-the-art measure because it can be calculated for all types of assets and allows for diversification. However, VALUE-at-risk is not a maximum loss number, so analysts may encounter losses greater than value-at-risk.
- Assumptions about historical sequences:
- Past yields are predictors of future yields, but there’s no guarantee that the historical record will show the worst and best of the future, but we use geometric averaging to convert prices into yields, so we’re looking at all the different weeks/months /… Returns are given equal weight to obtain the compound final value of investment returns in T years.
- If expected returns in asset prices are reasonable, then real returns should be normally distributed around those expectations. Investment management becomes easier when yields are well close to a normal distribution.
Define proof
Calculation of returns (PT is final price, P0 is initial price and dividend yield).
The price is dynamically converted to yield (2) and the expected yield (3) is calculated using a geometric time series (4) rather than an arithmetic average (the greater the fluctuation in yield, the greater the difference between arithmetic average and geometric average).
The normal distribution, which uses volatility as a measure of risk, is the square root of the variance (σ^2) of the weighted average of the realized returns of the investment. The weight is equal to the probability ps(6) of each case.
Finally, as described in “Investing” (Bodie, Kane, Marcus), VaR refers to the minimum cumulative loss of the left tail probability α and the right tail probability 1-α of the return distribution over a given time horizon.
In the variance-covariance method, we use the parametric method and assume that the returns are normally distributed. Therefore, we only need to calculate two parameters, namely the mean and SD (or standard deviation) of a given return.
The latter is useful for Excel calculations. We use the Average function to calculate the Average of returns, and STDEV will help us calculate the standard deviation. Finally, NORMINV will meet the goal of VaR calculation with a probability of 0.05 and 0.01 for VaR(95) and VaR(99), respectively.
Single portfolio VaR
In Python, the single-portfolio VaR calculation is not that complicated.
Import pandas as pd import numpy as NP import is preinstalled for each library with "PIP install * libraryName *" Yf. Download ('GOOG', '2010-01-01', Df ['return'] = close.pct_change () #VaR VaR_90 = norm.ppf(1-0.9, mean, Std_dev: print('VaR 90% trust: ', VaR_90)Copy the code
The final output would look like this:
Yahoo is a great way to get free financial data; another is Quandl’s API library.
To maintain continuity in the code structure, I present below a sample asset class and a multi-asset portfolio structure that includes VaR calculations.
Import numpy as NP import pandas as pd # Import bank data from the Quandl API (.4 represents the closing price) ticker = "WIKI/BAC.4" quandl.get(ticker, Sorted (percentage["Close"]) print ("99.99% actual loss not greater than ",percentile(order_percentage,.01) * 100)Copy the code
Output and VaR calculation.
moreassetsinvestmentPortfolio VaR
For multi-asset class portfolios:
# Expand the dataset to 5 different assets and combine them into a portfolio with alternative risk. [ "WIKI/NKE.4", "WIKI/NFLX.4", "WIKI/ AMzn.4 "] # Calculation of yield df.pct_change() # Different exposures into the portfolio percentage * ptF_Percentage = value_PTF [' value of the portfolio ']. Np. percentile(ptF_percentage,.01) print ("99.99% actual loss does not exceed: "Round (VaR, 2) print (" Expected loss over" + (ptf_percentage)) + "over" ptf_percentage)) + "days ")Copy the code
Expected Shortfall
Next we discuss the importance of another basic indicator: Expected Shortfall.
Search the literature on VAR and you’ll find a lot of criticism of VAR as a measure of market risk. You will inevitably see expected losses (ES) put forward as an alternative. What’s the difference between the two?
Assuming we evaluate our VAR (or, more simply, potential losses) at the 99% confidence level, we will have a series of loss outcomes at the 1% tail,
VAR answers the question: at the tail of 1%, what is the minimum loss over the entire result range? ES answers the question: at the tail of 1%, what is the average loss over the entire result range?
First, VaR.
VAR
If X is the payoff in h days, then, including. For example, for h=10 days of revenue,, we can calculate the 99% risk value from the normal distribution, as shown below
H = 10. # is 10 days MU_h = 0.1 # This is the average yield over 10 days - 10%. Sig = 0.3 # This is the fluctuation of the yield in one year - 30%. VaR_n = normppf(1-alpha)*sig_h - mu_hCopy the code
This is parameterized VaR, which means that we assume some distribution of returns. When using VAR, you usually use empirical VAR, which does not assume any distribution shape. In these cases, getting VaR is simply a matter of getting the necessary percentage.
VaR /Expected lossEXPECTED SHORTFALL
With VaR in mind, we can define the conditional VaR, or CVaR, or expected loss in the following way.
The explanation for this is simple. Basically, it’s the expected value of X.
If we assume another normal distribution, we can apply the following formula
Among themIs normally distributed,It’s a standard normal distributionQuartile.
And then we have ES.
# same as above alpha**-1 * norm.pdf(norm.ppf(alpha))* sig_h-mu_hCopy the code
We don’t have to assume a normal distribution.
The above assumption is a normal distribution, but we can also apply the student -T distribution. The derivation of the equivalent formula involves this problem. However, we can calculate the equivalent value of risk under the student -t distribution by the following formula
We can also assume a T-distribution.
Print (" 99%cvar ", (CVaR_t*100,2)Copy the code
The more degrees of freedom, the closer it is to a normal distribution.
Print ("99% VAR ", round(VaR_t*100,2)) print("99% VAR ", round(VaR_t*100,2))Copy the code
We can calculate similar results with actual market data. First, the data are fitted into normal distribution and T-distribution.
mu_norm, sig_norm = norm.fit(returns
Copy the code
The respective VaR and ES can be easily calculated.
Draw VaR and CVaR diagrams with different degrees of freedom
plt.plot(d[0], d[1]*100
plt.plot(np.arange(5, 100), VaR_n*np.ones(95)*100
Copy the code
VaR_n = norm.ppf(1-alpha)*sig_norm -munorm
Copy the code
The chart below gives a good idea of the difference between VaR and ES.
Python is indeed a powerful tool for computing and data visualization. It allows you to import several different pre-wrapped libraries, greatly reducing the complexity of other code such as C++.
Most welcome insight
1. Empirical research on R language fitting and prediction based on ArMA-GarCH-VAR model
2. Stochastic model of time-varying parameter VAR in R language
3. Empirical study on time series estimation of time-varying VAR model using R language
4. VAR fitting and prediction based on ARMA-GARCH process for R language
5. VaR comparison of GARCH (1,1), MA and historical simulation method
6. Vector autoregression (VAR) is used for impulse response of economic data in R language
7.R language to achieve vector automatic regression VAR model
8.R language random search variable selection SSVS estimation Bayesian vector autoregression (BVAR) model
9. Impulse response analysis of different types of VAR models in R language