Value at Risk (VaR) Analysis using the Historical Method with Python and yfinance
In this blog post, we will demonstrate how to perform Value at Risk (VaR) calculations using the historical method for a portfolio of stocks. We’ll use Python and the yfinance library to download historical stock price data and then calculate VaR for an equally weighted portfolio.
Setting Time Range and Tickers
First, let’s set the time range to a certain number of years and create a list of tickers we want to analyze. In this example, we’ll analyze the past 15 years of stock data.
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']
Downloading Adjusted Close Prices
Next, we will download the daily adjusted close prices for each ticker in our list using the yfinance library.
adj_close_df = pd.DataFrame()
for ticker in tickers:
data = yf.download(ticker, start=startDate, end=endDate)
adj_close_df[ticker] = data['Adj Close']
print(adj_close_df)
Calculating Daily Log Returns and Dropping NAs
Once we have the adjusted close prices, we can calculate the daily log returns for each stock and drop any NAs from the resulting DataFrame.
log_returns = np.log(adj_close_df / adj_close_df.shift(1))
log_returns = log_returns.dropna()
print(log_returns)
Creating an Equally Weighted Portfolio
Now, we’ll create an equally weighted portfolio with a total value of $1,000,000.
portfolio_value = 1000000
weights = np.array([1/len(tickers)]*len(tickers))
print(weights)
Calculating Historical Portfolio Returns
With the weights defined, we can now calculate the historical portfolio returns.
historical_returns = (log_returns * weights).sum(axis =1)
print(historical_returns)
Finding X-Day Historical Returns
Next, we’ll find the X-day historical returns. In this example, we’ll use a 50-day window.
days = 50
range_returns = historical_returns.rolling(window = days).sum()
range_returns = range_returns.dropna()
print(range_returns)
Calculating VaR Using the Historical Method
Now, we can specify a confidence interval and calculate the Value at Risk (VaR) using the historical method.
confidence_interval = 0.99
VaR = -np.percentile(range_returns, 100 - (confidence_interval * 100))*portfolio_value
print(VaR)
Plotting the Results of the Historical Returns
Finally, let’s plot the results of the historical returns to visualize the distribution of portfolio returns and the VaR at the specified confidence level.
return_window = days
range_returns = historical_returns.rolling(window=return_window).sum()
range_returns = range_returns.dropna()
range_returns_dollar = range_returns * portfolio_value
plt.hist(range_returns_dollar.dropna(), bins=50, density=True)
plt.xlabel(f'{return_window}-Day Portfolio Return (Dollar Value)')
plt.ylabel('Frequency')
plt.title(f'Distribution of Portfolio {return_window}-Day Returns (Dollar Value)')
plt.axvline(-VaR, color='r', linestyle='dashed', linewidth=2, label=f'VaR at {confidence_interval:.0%} confidence level')
plt.legend()
plt.show()
By following these steps, you can create a Python script that calculates the Value at Risk (VaR) using the historical method for your investment portfolio. Keep in mind that this approach is based on historical returns, which may not be a reliable indicator of future performance. 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, the historical method for calculating Value at Risk (VaR) provides a simple and intuitive way to estimate the potential losses in your investment portfolio. However, it is essential to remember that historical returns do not guarantee future performance, and relying solely on this method may lead to inaccurate risk assessments.
To develop a more comprehensive understanding of your portfolio’s risk, consider incorporating other risk management techniques such as Monte Carlo simulations, stress testing, and scenario analysis. By combining different approaches, you can create a more well-rounded risk management strategy that accounts for various market conditions and potential events. This holistic approach will enable you to make more informed investment decisions and better manage the potential risks and rewards associated with your investments.