Calculate relevance

# 使用numpy
import numpy as np
R = [0.01, 0.05, 0.02, -0.03]
var1 = np.var(R)
std1 = np.std(R)
#
# 使用pandas
import pandas as pd
R = pd.Series([0.01, 0.05, 0.02, -0.03])
var2 = R.var()
std2 = R.std()
import pandas as pd
import tushare as ts
pro = ts.pro_api()
wanke = pro.daily(ts_code='000002.SZ', start_date='20170101')
pingan = pro.daily(ts_code='601318.SH', start_date='20170101')
wanke.head()

#下行风险
def cal_downside_risk(r):
    _r = r.map(lambda x: x / 100)
    mean = _r.mean()
    r_adjust = _r.map(lambda x: min(x-mean, 0))
    risk = np.sqrt((r_adjust ** 2).mean())
    return risk
 
wanke_risk = cal_downside_risk(wanke.pct_chg)
pingan_risk = cal_downside_risk(pingan.pct_chg)
print('万科下行风险:', wanke_risk)
print('平安下行风险:', pingan_risk)
#风险价值
# 历史模拟法
wanke_var = wanke.pct_chg.quantile(0.05) / 100
pingan_var = pingan.pct_chg.quantile(0.05) / 100
print('历史模拟法')
print('万科VaR(0.05,1天):', wanke_var)
print('平安VaR(0.05,1天):', pingan_var)
#
# 协方差矩阵法
from scipy.stats import norm
wanke_var = norm.ppf(0.05, wanke.pct_chg.mean(), 
 wanke.pct_chg.std()) / 100
pingan_var = norm.ppf(0.05, pingan.pct_chg.mean(), 
 pingan.pct_chg.std()) / 100
print('协方差矩阵法')
print('万科VaR(0.05,1天):', wanke_var)
print('平安VaR(0.05,1天):', pingan_var)
, the quantile() method of the pandas Series object will return the quantile. We have made it clear earlier that the historical simulation method can calculate VaR directly to find the 0.05 quantile; the mean() method and std() method of the pandas Series object return Its mean and standard deviation; the scipy.stats.norm function can find the corresponding quantile based on the confidence interval, mean and standard deviation we input.
#期望亏空
VaR_wanke = wanke.pct_chg.quantile(0.05)
ES_wanke = wanke.query('pct_chg <= @VaR_wanke')['pct_chg'].mean()
print('万科近两年风险价值:', VaR_wanke)
print('万科近两年期望亏空:', ES_wanke)
#最大回撤
import pandas as pd
import tushare as ts
pro = ts.pro_api()
index_sh = pro.index_daily(ts_code='000001.SH', start_date='20180101')
index_sh.index = pd.to_datetime(index_sh.trade_date)
index_sh = index_sh.sort_index(ascending=True)
index_sh.head()
value = (index_sh.pct_chg / 100 + 1).cumprod()
value.plot();
MDD = (value.cummax() - value).max()
print('最大回撤:', MDD)
mdd = ((value.cummax() - value) / value.cummax()).max()
print('最大回撤率:', mdd)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324323533&siteId=291194637