VaR_and_ES.ipynb

!pip install yfinance #설치
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats
import yfinance as yf

Historical simulation (non-parametric VaR)

aapl = yf.download('AAPL', '2020-01-01')['Adj Close'] #애플의 종가 불러오기
aapl

[100%**] 1 of 1 completed

Date 2020-01-02 73.894333 2020-01-03 73.175926 2020-01-06 73.758995 2020-01-07 73.412109 2020-01-08 74.593056 ... 2022-03-24 174.070007 2022-03-25 174.720001 2022-03-28 175.600006 2022-03-29 178.960007 2022-03-30 177.770004 Name: Adj Close, Length: 566, dtype: float64

aapl = aapl[-501:] #총 501개의 최신 데이터
aapl = aapl.pct_change() #퍼센트 변화로 나타냄
aapl.dropna(inplace = True)
aapl

Date 2020-04-07 -0.011583 2020-04-08 0.025595 2020-04-09 0.007216 2020-04-13 0.019628 2020-04-14 0.050503 ... 2022-03-24 0.022678 2022-03-25 0.003734 2022-03-28 0.005037 2022-03-29 0.019134 2022-03-30 -0.006650 Name: Adj Close, Length: 500, dtype: float64

desc = aapl.describe()
desc.loc['var'] = aapl.var()
desc.loc['skew'] = aapl.skew()
desc.loc['kurt'] = aapl.kurtosis()
desc

count 500.000000 mean 0.002207 std 0.019253 min -0.080061 25% -0.008422 50% 0.001480 75% 0.013725 max 0.104689 var 0.000371 skew 0.131979 kurt 2.403142 Name: Adj Close, dtype: float64

aapl.std() * np.sqrt(252) #연간 변동성

0.30562705669977386

plt.plot(abs(aapl)); #시각화

Untitled

plt.hist(aapl, bins=30);#히스토그램으로 시각화

Untitled

rtns = aapl.sort_values() #안좋은 순서대로 나타내기
rtns

Date 2020-09-03 -0.080061 2020-09-08 -0.067295 2020-10-30 -0.056018 2020-06-11 -0.048010 2020-10-28 -0.046312 ... 2020-08-21 0.051532 2021-03-01 0.053851 2020-10-12 0.063521 2022-01-28 0.069778 2020-07-31 0.104689 Name: Adj Close, Length: 500, dtype: float64

#99% 신뢰수준에서 1일 VaR(%)
historical_VaR = rtns[4]
round(historical_VaR,4)