# Tecdat: Python Monte Carlo simulation of portfolio value at risk (VaR)

Time：2021-7-8

## Link to the original text:http://tecdat.cn/?p=22862

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

## VaR in financial and portfolio risk management?

VaR is the abbreviation of “value at risk”, which is used by many companies and banks to determine the level of financial risk within their companies. VaR is calculated for the company’s investment, and may also be used to check the risk level of the portfolio managed by the bank or the company.

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

Value at risk is the minimum loss or the maximum loss that will be achieved at a certain probability level (confidence interval). The image above shows a company in the α% The maximum possible loss under the confidence level of. At the individual level, VAR can help you predict or analyze the maximum loss your portfolio may face.

## Monte Carlo simulation

The Monte Carlo model is the result of the efforts of Stanislaw Ulam and John Neumann, who developed this model after the Second World War. The model is named after a gambling city in Monaco, because there are opportunities and randomness in gambling.

Monte Carlo simulation is a probability model, which uses the generated random variables and economic factors (expected rate of return, volatility) to predict the results. The model is often used to calculate risk and uncertainty.

We will now use Monte Carlo simulation to generate a set of forecast returns for our portfolio, which will help us find out the value at risk of our investment.

## Calculating VaR in Python

We’ll start by importing the required libraries and functions

``````#Import all required libraries
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd``````

For the purpose of our project, I have considered the stocks of the past two years.

`````` for i in range(len):  web.get_data(tickers\[i\]
stocks.tail()`````` Next, we will calculate the portfolio weight for each asset. Asset weights can be calculated by achieving the maximum Sharpe ratio.

``````#Annualized yield
historical_return(stocks)
#Sample variance of portfolio
sample_ CoV # sharp ratio
EffFro(mu,   Sigma,   weight_ bounds=(0,1))  # The weight limit of negative numbers allows short stocks
max_ sharpe()  # You can use the increase target to ensure the minimum zero weight of a single stock`````` ## Asset weight of maximum Sharpe ratio

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

``````#Var calculation
rx2  = \[\]# Asset weight in exchange for maximum Sharpe ratio
list(sharpe.values())``````

Now, we will convert the stock price of the portfolio into cumulative return, which can also be regarded as the holding period return (HPR) of the project.

``   tick  = (tick  +1).cumprod()`` ``````#Plot the cumulative / HPR of all stocks
tick\[col\].plot()plt`````` Now, we’ll pick out the latest HPR for each asset and use the. Dot() function to multiply the yield by the calculated asset weight.

``````sigma = pre.std()
price=price.dot(sh_ wt)  # Calculate the weighted value`````` After calculating the expected return and volatility (standard deviation of expected return) of the portfolio, we will set up and run the Monte Carlo simulation. I used 1440 minutes a day, and the simulation ran 20000 times. The time step can be changed as required. 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)`````` Profit range of one day in 1440 minutes | red – minimum loss | green – Minimum Profit

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

``````plt.hist(returns)
plt.show()`````` Output the accurate values of the upper and lower limits, and assuming that our portfolio value is 1000 yuan, we will calculate the amount of funds that should be retained to make up for our minimum loss.

``print(percentile(   returns,5),percentile(   returns,95))   VaR  -  Under the 5% probability, the minimum loss is 5.7%. Similarly, under the 5% probability, the return can be higher than 15%`` The minimum loss per day is 1.29%, with a probability of 5%.

The amount you get will mark the amount you need to make up for your loss every day. This result can also be explained as the lowest loss your portfolio will face with a 5% probability.

## summary

The above method shows how we calculate the value at risk (VaR) of a portfolio. For the use of modern portfolio theory (MPT) to calculate a certain number of portfolios, help to consolidate your understanding of portfolio analysis and optimization. Finally, VaR and Monte Carlo simulation model can also be used to predict the loss and income through the stock price. This can be achieved by multiplying the resulting daily return value by the final price of the respective stock. Most popular insights

1.Empirical research on fitting and forecasting of R language based on arma-garch-var model

## Java Engineer Interview Questions

The content covers: Java, mybatis, zookeeper, Dubbo, elasticsearch, memcached, redis, mysql, spring, spring boot, springcloud, rabbitmq, Kafka, Linux, etcMybatis interview questions1. What is mybatis?1. Mybatis is a semi ORM (object relational mapping) framework. It encapsulates JDBC internally. During development, you only need to pay attention to the SQL statement itself, and you don’t need to […]