# import libraries
import yfinance as yf
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
# download price history
AAPL = yf.download('AAPL', start='2022-01-01').Close
plt.figure()
AAPL.plot()
# calculate returns
rets = np.log(AAPL/AAPL.shift(1))
rets.dropna(inplace=True)
plt.figure()
rets.plot()
plt.figure()
plt.hist(rets,50)
# fit normal distribution
mu, std = norm.fit(rets)
x = np.linspace(-1, 1, 100)
p = norm.pdf(x, mu, std)
plt.plot(x, p, 'k', linewidth=2)
# calculate next day VaR and ES
h = 1
alpha = 0.01
CVaR = alpha**-1 * norm.pdf(norm.ppf(alpha))*std - mu
VaR = norm.ppf(1-alpha)*std - mu
print('VaR = %2.2f %%'%(VaR*100))
print('ES = %2.2f %%'%(CVaR*100))
Have questions? I will be happy to help!
You can ask me anything. Just maybe not relationship advice.
I might not be very good at that. 😁