## Estimating Value at Risk with Python Using the Parametric Method

In this blog article, we will demonstrate how to calculate the Value at Risk (VaR) for a portfolio of stocks using the parametric method, also known as the variance-covariance method. The parametric method estimates VaR by assuming that portfolio returns follow a normal distribution. We will use Python and the yfinance library to download historical stock data and perform the calculations.

#### Set Timeframe and Define Tickers

First, we will define the time range for our analysis and create a list of tickers we want to include in our portfolio:

```				```
import numpy as np
import pandas as pd
import datetime as dt
import yfinance as yf

years = 15

endDate = dt.datetime.now()
startDate = endDate - dt.timedelta(days=365*years)

tickers = ['SPY', 'BND', 'GLD', 'QQQ', 'VTI']

```
```

Next, we will download the daily adjusted close prices for each ticker and calculate the daily log returns:

```				```
for ticker in tickers:

log_returns = log_returns.dropna()

```
```

#### Create Equally Weighted Portfolio and Calculate Historical Returns

We will create an equally weighted portfolio and calculate the historical returns for this portfolio:

```				```
portfolio_value = 1000000
weights = np.array([1/len(tickers)] * len(tickers))

historical_returns = (log_returns * weights).sum(axis=1)

```
```

#### Find X-Day Historical Returns

We will find the rolling sum of historical returns for a specified number of days:

```				```
days = 5
historical_x_day_returns = historical_returns.rolling(window=days).sum()

```
```

#### Create Covariance Matrix and Calculate Portfolio Standard Deviation

Now, we will create a covariance matrix for all the securities and calculate the portfolio standard deviation:

```				```
cov_matrix = log_returns.cov() * 252
portfolio_std_dev = np.sqrt(weights.T @ cov_matrix @ weights)

```
```

#### Calculate VaR at Different Confidence Levels

We will calculate the Value at Risk (VaR) at different confidence levels:

```				```
from scipy.stats import norm

confidence_levels = [0.90, 0.95, 0.99]

VaRs = []
for cl in confidence_levels:
VaR = portfolio_value * portfolio_std_dev * norm.ppf(cl) * np.sqrt(days / 252)
VaRs.append(VaR)

```
```

#### Print VaR Results

Let’s print the VaR results for each confidence level:

```				```
print(f'{"Confidence Level":<20} {"Value at Risk":<20}')
print('-' * 40)

for cl, VaR in zip(confidence_levels, VaRs):
print(f'{cl * 100:>6.0f}%: {"":<8} \${VaR:>10,.2f}')

```
```

#### Plot the Distribution of Portfolio Returns and Parametric VaR Estimates

Finally, we will plot the distribution of the X-day portfolio returns and the parametric VaR estimates:

```				```
plt.hist(historical_x_day_returns, bins=50, density=True, alpha=0.5, label=f'{days}-Day Returns')

plt.xlabel(f'{days}-Day Portfolio Return')
plt.ylabel('Frequency')
plt.title(f'Distribution of Portfolio {days}-Day Returns and Parametric VaR Estimates')
plt.legend()
plt.show()

```
```

By following these steps, you can create a Python script that calculates the Value at Risk (VaR) using the parametric method for your investment portfolio. Keep in mind that this approach assumes that portfolio returns follow a normal distribution, which may not always hold true. Continuously refining your analysis and considering other factors will help you develop a more accurate understanding of the risks associated with your investments, enabling you to make more informed decisions.

In conclusion, calculating Value at Risk (VaR) using the parametric method can provide you with a useful metric for understanding and managing the potential risks associated with your investment portfolio. By incorporating this approach into your analysis, you can better anticipate potential losses and make more informed decisions about your investments. However, always remember that the underlying assumptions of this method, such as the normal distribution of portfolio returns, may not always be valid. As an investor, it’s essential to keep refining your analysis, stay informed about market conditions, and explore other risk management techniques to ensure that you’re effectively managing the potential risks and rewards of your investments.

## Hire me for your next Project

I can assist you with your financial modeling and quantitative finance projects, leveraging my expertise and experience in the field. ## Contact Me

Feel free to reach out to discuss your freelance project needs, and let’s collaborate on bringing your vision to life! 