In our previous post we explained what Value at risk is. In this post I can show you how to calculate it for your robinhood portfolio. As always my goal is to have these automated to have minimal effort on your part so there will be some code involved but Im going to make it as easy and succinct as possible.
Im using Robinhood here as an example but it really can be applied to any brokerage where you can download your holdings as a csv.
Lets get started –
Im assuming you have a csv with ticker and your current value. Sadly Robinhood doesnt have a way to automatically export your data. I’ll keep looking and update this post if I figured out a way to automatically pull this data from Robinhood. Make sure the input csv looks like this – (illustrative purposes only)
ticker,value
AAPL,1000
MSFT,5000
NVDA,2000
VaR = Portfolio Value * z-score * Portfolio Standard Deviation
Here is the code
You need to install 4 modules – pip install <x> – pandas, scipy and yfinance
import pandas as pd
import numpy as np
from scipy.stats import norm
import yfinance as yf
def load_data():
df = pd.read_csv('raw_data/robinhood.csv')
return df
def calculate_var(dataframe, confidence_level=0.95):
"""
Calculate Value at Risk (VaR) using covariance method.
Parameters:
dataframe (pd.DataFrame): DataFrame with 'ticker' and 'value' columns.
confidence_level (float, optional): Confidence level for VaR calculation (default is 0.95).
Returns:
float: Value at Risk (VaR) at the given confidence level.
"""
# Fetch historical prices for each stock ticker
prices_data = {}
for ticker in dataframe['ticker']:
stock_data = yf.download(ticker, start='2020-01-01', end='2023-01-01')
prices_data[ticker] = stock_data['Open']
# Create a DataFrame with historical prices
prices_dataframe = pd.DataFrame(prices_data)
# Calculate the total portfolio value
total_portfolio_value = dataframe['value'].sum()
# Calculate the returns for each stock
returns_dataframe = prices_dataframe.pct_change()
# Combine returns with the original DataFrame
merged_df = pd.concat([dataframe, returns_dataframe], axis=1)
# Drop NaNs from the merged DataFrame
merged_df.dropna(inplace=True)
# Calculate the mean and covariance matrix of returns
mean_returns = returns_dataframe.mean()
cov_matrix = returns_dataframe.cov()
# Calculate the portfolio standard deviation
portfolio_std_dev = np.sqrt(
np.dot(dataframe['value'], np.dot(cov_matrix, dataframe['value']))) / total_portfolio_value
# Calculate the Z-score corresponding to the confidence level
z_score = norm.ppf(1 - confidence_level)
# Calculate VaR
var_value = -1 * total_portfolio_value * z_score * portfolio_std_dev
return var_value
if __name__ == "__main__":
df = load_data()
print(calculate_var(df))
The code calculates the Value at Risk (VaR) for an investment portfolio. It fetches historical price data for each stock ticker, computes daily returns, and merges them with the original portfolio values. By dropping any rows with missing data, the algorithm ensures accurate calculations.
The VaR is estimated using the mean returns, covariance matrix, and a specified confidence level. It represents the potential loss the portfolio may experience with a certain probability over the given time horizon. The result can be interpreted as the maximum amount the portfolio is expected to lose at the specified confidence level, serving as a powerful tool for risk assessment in financial decision-making.
What does this result mean? It depends on the confidence level you put as input. If confidence level is 0.95 and the result is $1000 it means for 95% of the time, your portfolio wont loose more than $1000 in value. The intuition may be simple but this is an extremely powerful tool used by major businesses in order to keep accurate track of how much risk they are taking. You can use it to measure the risk tolerance of your portfolio as well.The result of the calculated Value at Risk (VaR) holds crucial implications depending on the confidence level specified as input. For instance, if a confidence level of 0.95 is used, and the VaR result amounts to $1000, it signifies that, with 95% probability, your portfolio’s value will not decline beyond $1000 over the given time horizon. While the concept may seem straightforward, its significance is far-reaching, as it serves as a potent instrument relied upon by major businesses to maintain a meticulous grasp on the level of risk they are exposed to in their investments. Notably, VaR is not only a tool for big players; it also empowers individual investors to gauge their portfolio’s risk tolerance. With this insight, investors can navigate the financial landscape with greater confidence and align their risk appetite with their aspirations and goals. The VaR’s role in evaluating potential losses and risk profiles makes it a vital ally in the dynamic world of finance, guiding decisions and strategies to embrace opportunities while safeguarding against undue vulnerabilities.
Happy Investing!
Disclaimer: The information provided here is for general informational purposes only and should not be considered as professional financial or investment advice. Before making any financial decisions, including investments, it is essential to seek advice from a qualified financial advisor or professional.
Leave a comment