Original link:tecdat.cn/?p=22862 

Original source:Tuo End number according to the tribe public number

How to use Python to automatically calculate value at risk (VaR) through Monte Carlo simulations to manage the financial risk of a portfolio or stock.

VaR in finance and portfolio Risk Management?

VaR, short for “value at risk,” is a tool many companies and banks use to determine the level of financial risk within their firms. Var is calculated for a company’s investments and may also be used to check the level of risk in the portfolio managed by a bank or company.

The calculation can be considered as a statistical method. It can also be simplified to the following statement

Value at risk is the minimum loss that will be incurred or the maximum loss that will be realized at a certain probability level (confidence interval).

The figure above shows the maximum loss a company could face at an alpha % confidence level. On a personal level, VaR can help you predict or analyze the maximum losses your portfolio could face.

Monte Carlo simulation

The Monte Carlo model is the brainchild of Stanislaw Ulam and John Neumann, who developed it after The Second World War. The model is named after a gambling city in Monaco because of the chance and randomness involved in gambling.

Monte Carlo simulation is a probabilistic model that uses the resulting random variables and economic factors (expected rate of return, volatility) to predict outcomes. The model is often used to calculate risk and uncertainty.

We will now use Monte Carlo simulations to generate a set of predicted returns for our portfolio, which will help us figure out the value-at-risk of our investments.


Evaluate VaR in Python

We will start by importing the required libraries and functions

Import matplotlib.pyplot as PLT import numpy as NP import pandas as pdCopy the code

For the purposes of our project, I looked at stocks for the past two years.

 
for i in range(len):  web.get_data(tickers[i] 
stocks.tail()
Copy the code

 

Next, we will calculate the portfolio weight for each asset. Asset weights can be calculated by achieving the maximum Sharpe ratio.

# Annualized return historical_return(stocks) # Sample variance of portfolio sample_COv # Sharpe ratio EffFro(mu, Sigma, The weight_bounds=(0,1)) # negative weight bounds allow shorting stocks max_sharpe() # can be used to increase the target to ensure a minimum zero weight for individual stocksCopy the code

Asset weights for the maximum Sharpe ratio

Asset weights will be used to calculate the expected return of the portfolio.

Rx2 = []# value () # value ()Copy the code

We will now convert the stock price of the portfolio into cumulative income, which can also be considered the holding period (HPR) of the project.

   tick  = (tick  +1).cumprod()
 
Copy the code

Tick [col].plot() PLTCopy the code

Now we will pick out the latest HPR for each asset and multiply the return rate by the calculated weight of the asset using the.dot() function.

Sigma = pre-std () price=price. Dot (sh_wt) # calculate the weighted valueCopy the code

After calculating the portfolio’s expected return and volatility (the standard deviation of expected return), we will set up and run a Monte Carlo simulation. The time I used was 1440 (minutes in a day) and the simulation ran 20,000 times. The time step can be changed on request. I used a 95% confidence interval.

For j in range(20000): #20000 simulation runs (RTN /Time,sigma/ SQRT (Time),Time) PLT (np.percentile(daily_returns,5)Copy the code

1440 minutes a day of gains range – minimum loss | | red green – minimum income

Visualizing the distribution of yields, we can see the following chart

plt.hist(returns)
plt.show()
Copy the code

Output the exact values of the upper and lower limits, and assuming our portfolio is worth $1000, we will calculate the amount of money we should keep to cover our minimum losses.

Print (Percentile (Returns,5), Percentile (Returns,95)) VaR - With a 5% probability, the minimum loss is 5.7%. Similarly, with a 5% probability, the gain can be greater than 15%Copy the code

The minimum daily loss is 1.29%, with a 5% probability.

The amount received will mark the amount needed each day to make up for your loss. This result can also be interpreted as the minimum loss your portfolio will face with a 5% probability.

conclusion

The above method shows how we calculate the value at risk (VaR) of a portfolio. The use of modern portfolio theory (MPT) to calculate a number of portfolios helps solidify your understanding of portfolio analysis and optimization. Finally, VaR is used in conjunction with Monte Carlo simulation models and can also be used to predict losses and gains from stock prices. This can be done by multiplying the resulting daily earnings by the final price of each stock.


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