Files
strategy-lab/to_explore/pyquantnews/5_ValueAtRisk.ipynb
David Brazda e3da60c647 daily update
2024-10-21 20:57:56 +02:00

7.6 KiB

No description has been provided for this image

This code calculates the Value at Risk (VaR) for a portfolio of stocks. It downloads historical stock data, computes daily returns, and calculates the portfolio's mean return and standard deviation. The code uses these metrics to compute the potential maximum loss (VaR) at a specified confidence interval. Additionally, it plots the VaR over a 30-day period, providing a visual representation of the risk. This is useful for risk management and financial planning.

In [ ]:
import pandas as pd
import numpy as np
from scipy.stats import norm
import matplotlib.pyplot as plt
In [ ]:
import yfinance as yf

Define the portfolio of stocks and their respective weights. The weights must sum to 1.

In [ ]:
tickers = ["AAPL", "FB", "C", "DIS"]
weights = np.array([0.25, 0.3, 0.15, 0.3])

Define the initial investment amount and confidence interval for VaR calculation.

In [ ]:
initial_investment = 1_000
confidence = 0.05

Download historical stock data for the specified tickers and date range. Filter to close prices only.

In [ ]:
data = yf.download(tickers, start="2018-01-01", end="2021-12-31")
data = data.Close

Calculate the daily returns for each stock in the portfolio.

In [ ]:
returns = data.pct_change()

Compute the covariance matrix of the stock returns to understand the variance and correlation.

In [ ]:
cov_matrix = returns.cov()

Compute the mean daily returns for each stock in the portfolio.

In [ ]:
mean_returns = returns.mean()

Calculate the portfolio's expected mean return using the weighted average of individual stock returns.

In [ ]:
port_mean = mean_returns.dot(weights)

Calculate the portfolio's standard deviation to measure the overall risk.

In [ ]:
port_stdev = np.sqrt(weights.T.dot(cov_matrix).dot(weights))

Compute the mean investment return based on the initial investment and expected portfolio return.

In [ ]:
mean_investment = (1 + port_mean) * initial_investment

Calculate the standard deviation of the investment returns to assess the volatility in dollar terms.

In [ ]:
investment_stdev = initial_investment * port_stdev

Calculate the percent point function (PPF) for the given confidence interval.

In [ ]:
percent_point = norm.ppf(confidence, mean_investment, investment_stdev)

Calculate the Value at Risk (VaR) at the specified confidence interval.

In [ ]:
value_at_risk = initial_investment - percent_point

Display the calculated VaR for the portfolio.

In [ ]:
f"Portfolio VaR: {value_at_risk}"

Calculate the VaR over a 30-day period by scaling with the square root of time.

In [ ]:
value_at_risks = value_at_risk * np.sqrt(range(1, 31))

Plot the VaR over a 30-day period to visualize potential maximum loss over time.

In [ ]:
plt.xlabel("Day")
plt.ylabel("Max loss")
plt.title("Portfolio VaR")
plt.plot(value_at_risks, "r")

PyQuant News is where finance practitioners level up with Python for quant finance, algorithmic trading, and market data analysis. Looking to get started? Check out the fastest growing, top-selling course to get started with Python for quant finance. For educational purposes. Not investment advise. Use at your own risk.