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

337 lines
7.6 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"id": "0914f29a",
"metadata": {},
"source": [
"<div style=\"background-color:#000;\"><img src=\"pqn.png\"></img></div>"
]
},
{
"cell_type": "markdown",
"id": "febfac35",
"metadata": {},
"source": [
"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."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b182fa6a",
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n",
"import numpy as np\n",
"from scipy.stats import norm\n",
"import matplotlib.pyplot as plt"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "10edf2bd",
"metadata": {},
"outputs": [],
"source": [
"import yfinance as yf"
]
},
{
"cell_type": "markdown",
"id": "f4ba67b6",
"metadata": {},
"source": [
"Define the portfolio of stocks and their respective weights. The weights must sum to 1."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c1351a91",
"metadata": {},
"outputs": [],
"source": [
"tickers = [\"AAPL\", \"FB\", \"C\", \"DIS\"]\n",
"weights = np.array([0.25, 0.3, 0.15, 0.3])"
]
},
{
"cell_type": "markdown",
"id": "8f730b65",
"metadata": {},
"source": [
"Define the initial investment amount and confidence interval for VaR calculation."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "8a2aadea",
"metadata": {},
"outputs": [],
"source": [
"initial_investment = 1_000\n",
"confidence = 0.05"
]
},
{
"cell_type": "markdown",
"id": "0c784214",
"metadata": {},
"source": [
"Download historical stock data for the specified tickers and date range. Filter to close prices only."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "5e93c03c",
"metadata": {},
"outputs": [],
"source": [
"data = yf.download(tickers, start=\"2018-01-01\", end=\"2021-12-31\")\n",
"data = data.Close"
]
},
{
"cell_type": "markdown",
"id": "4ea34632",
"metadata": {},
"source": [
"Calculate the daily returns for each stock in the portfolio."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "61270dc0",
"metadata": {},
"outputs": [],
"source": [
"returns = data.pct_change()"
]
},
{
"cell_type": "markdown",
"id": "66e7b41d",
"metadata": {},
"source": [
"Compute the covariance matrix of the stock returns to understand the variance and correlation."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "684cfbf6",
"metadata": {},
"outputs": [],
"source": [
"cov_matrix = returns.cov()"
]
},
{
"cell_type": "markdown",
"id": "604a1970",
"metadata": {},
"source": [
"Compute the mean daily returns for each stock in the portfolio."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7fc27a88",
"metadata": {},
"outputs": [],
"source": [
"mean_returns = returns.mean()"
]
},
{
"cell_type": "markdown",
"id": "c07ff0af",
"metadata": {},
"source": [
"Calculate the portfolio's expected mean return using the weighted average of individual stock returns."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ff9bbcb1",
"metadata": {},
"outputs": [],
"source": [
"port_mean = mean_returns.dot(weights)"
]
},
{
"cell_type": "markdown",
"id": "a10bde64",
"metadata": {},
"source": [
"Calculate the portfolio's standard deviation to measure the overall risk."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "55c75e3a",
"metadata": {},
"outputs": [],
"source": [
"port_stdev = np.sqrt(weights.T.dot(cov_matrix).dot(weights))"
]
},
{
"cell_type": "markdown",
"id": "756c6dc7",
"metadata": {},
"source": [
"Compute the mean investment return based on the initial investment and expected portfolio return."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "81e66c7b",
"metadata": {},
"outputs": [],
"source": [
"mean_investment = (1 + port_mean) * initial_investment"
]
},
{
"cell_type": "markdown",
"id": "6e08e709",
"metadata": {},
"source": [
"Calculate the standard deviation of the investment returns to assess the volatility in dollar terms."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a411b301",
"metadata": {},
"outputs": [],
"source": [
"investment_stdev = initial_investment * port_stdev"
]
},
{
"cell_type": "markdown",
"id": "809d85fd",
"metadata": {},
"source": [
"Calculate the percent point function (PPF) for the given confidence interval."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6bc37ef2",
"metadata": {},
"outputs": [],
"source": [
"percent_point = norm.ppf(confidence, mean_investment, investment_stdev)"
]
},
{
"cell_type": "markdown",
"id": "09805c37",
"metadata": {},
"source": [
"Calculate the Value at Risk (VaR) at the specified confidence interval."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2c79e0c0",
"metadata": {},
"outputs": [],
"source": [
"value_at_risk = initial_investment - percent_point"
]
},
{
"cell_type": "markdown",
"id": "7e537935",
"metadata": {},
"source": [
"Display the calculated VaR for the portfolio."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "58065b04",
"metadata": {},
"outputs": [],
"source": [
"f\"Portfolio VaR: {value_at_risk}\""
]
},
{
"cell_type": "markdown",
"id": "95a6e6d7",
"metadata": {},
"source": [
"Calculate the VaR over a 30-day period by scaling with the square root of time."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7e6e2859",
"metadata": {},
"outputs": [],
"source": [
"value_at_risks = value_at_risk * np.sqrt(range(1, 31))"
]
},
{
"cell_type": "markdown",
"id": "5147f76c",
"metadata": {},
"source": [
"Plot the VaR over a 30-day period to visualize potential maximum loss over time."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "de3d7ef3",
"metadata": {},
"outputs": [],
"source": [
"plt.xlabel(\"Day\")\n",
"plt.ylabel(\"Max loss\")\n",
"plt.title(\"Portfolio VaR\")\n",
"plt.plot(value_at_risks, \"r\")"
]
},
{
"cell_type": "markdown",
"id": "04e96fbc",
"metadata": {},
"source": [
"<a href=\"https://pyquantnews.com/\">PyQuant News</a> 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 <a href=\"https://gettingstartedwithpythonforquantfinance.com/\">get started with Python for quant finance</a>. For educational purposes. Not investment advise. Use at your own risk."
]
}
],
"metadata": {
"jupytext": {
"cell_metadata_filter": "-all",
"main_language": "python",
"notebook_metadata_filter": "-all"
}
},
"nbformat": 4,
"nbformat_minor": 5
}