Measuring Equity Risk
TBC
- Import packages and setup configurations
- Collect prices from the stock price API
- Build a dataframe from the stock prices
- Calculate stock variance
- Plot the returns distributions
- Value at Risk (VaR)
In this notebook we'll explore two statistical methods for calculating Equity Risk:
- Variance: fluctuation of stock return from its mean
- VaR: the maximum an investor could loose (within a confidence interval)
For the purposes of this notebook, we'll explore the above looking at the risk of Apple (ticker = AAPL).
import requests
import json
import datetime
import os
# Import data wrangling packages
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# Use Python's "magic" commands since we want to see the graphs within this notebook
%matplotlib inline
%pylab inline
# Plot configuration
plt.style.use('fivethirtyeight')
pylab.rcParams["figure.figsize"] = (10,8)
API_KEY = os.getenv("AV_API_KEY")
def get_adj_prices(symbol):
url = f"https://www.alphavantage.co/query?function=TIME_SERIES_WEEKLY_ADJUSTED&symbol={symbol}&apikey={API_KEY}"
raw_data = requests.get(url).text
json_data = json.loads(raw_data)["Weekly Adjusted Time Series"]
return json_data
def build_stock_df(symbol):
json_data = get_adj_prices(symbol)
df = pd.DataFrame.from_dict(json_data).transpose()
adj_col = "5. adjusted close"
df = df[[adj_col]].rename(columns={adj_col: f"price_{symbol}"})
return df
aapl = build_stock_df("aapl").head(1000)
spy = build_stock_df("spy").head(1000)
ts_df = aapl.join(spy).astype(float)
ts_df["aapl_returns"] = ts_df["price_aapl"].pct_change(1)
ts_df["spy_returns"] = ts_df["price_spy"].pct_change(1)
ts_df.head(5)
# The minimum return was -6.5% and the max 8.2%
aapl_summary = ts_df["aapl_returns"].describe()
aapl_summary
ts_df["aapl_returns"].hist(bins=50, figsize=(8,6))
# Lets check on what date AAPL had a min and max return
max_date = ts_df.loc[ts_df['aapl_returns'].idxmax()].name
min_date = ts_df.loc[ts_df['aapl_returns'].idxmin()].name
print ("The max value for aapl was recorded on {} while the min value was recorded on {}".format(max_date, min_date))
snp_summary = ts_df["spy_returns"].describe()
snp_summary
style.use('fivethirtyeight')
x = ts_df["spy_returns"] * 100
y = ts_df["aapl_returns"] * 100
plt.hist(x, alpha = 0.5, bins=50, label='S&P 500')
plt.hist(y,alpha = 0.5, bins = 50, label='Apple Inc.')
plt.legend(loc='upper right')
plt.tick_params(axis = 'both', which = 'major', labelsize = 9)
plt.axhline(y = 0, color = 'black', linewidth = 5, alpha = 1)
#plt.xlabel(s = "% return", fontsize = "small")
plt.text(-15, 180, s = """This grap plots the distribution of weeklyreturns of Apple Inc. against
returns of the S&P 500 between 2003-07-25 and today.
The histogram for Apple Inc. is more dispersed, with more extreme
highs and lows. During this period, Apple Inc. had a high of 32%
and a low of -16%.""", fontsize = 15, alpha = .75)
plt.text(-15, 215, s = """Plotting return distributions""", weight = "bold", fontsize = 25, alpha = .75)
plt.show()
def var_cov_var(P, c, m, sigma):
"""
Variance-Covariance calculation of weekly Value-at-Risk
using confidence level c, with mean of returns m
and standard deviation of returns sigma, on a portfolio
of value P.
"""
alpha = norm.ppf(1-c, m, sigma)
return P - P*(alpha + 1)
from scipy.stats import norm
P = 1000000 # 1,000,000 USD
c = 0.99 # 99% confidence interval
aapl_mean = ts_df["aapl_returns"].mean()
aapl_sigma = ts_df["aapl_returns"].std()
snp_mean = ts_df["spy_returns"].mean()
snp_sigma = ts_df["spy_returns"].std()
var_aapl = var_cov_var(P, c, aapl_mean, aapl_sigma)
var_snp = var_cov_var(P, c, snp_mean, snp_sigma)
print ("The one week VaR for Apple on a $1 million portfolio is ${:,.2f}".format(round(var_aapl,2)))
print ("The one week VaR for the S&P 500 on a $1 million portfolio is ${:,.2f}".format(round(var_snp,2)))