目录
1. 产品描述并生成产品
2. 计算产品的年化收益率、年化波动率
3. 计算产品的历史日收益率
4. 计算产品的日VaR
5. 计算产品的最大回撤
6. 计算产品的夏普比率
7. 计算产品的Beta值(β)和Jensen's Alpha(α)
8. 计算产品的特雷诺比率
9. 绘制产品净值曲线
数据:
1.1 产品需求:某个客户需要9%的收益率,对该客户进行组合优化配置,设计适合该客户的金融产品雏形
1.2 设计符合要求的产品
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
df_004 = pd.read_csv('600004.csv',encoding='utf-8')
df_015 = pd.read_csv('600015.csv',encoding='utf-8')
df_023 = pd.read_csv('600023.csv',encoding='utf-8')
df_033 = pd.read_csv('600033.csv',encoding='utf-8')
df_343 = pd.read_csv('600343.csv',encoding='utf-8')
df_346 = pd.read_csv('600346.csv',encoding='utf-8')
df_183 = pd.read_csv('600183.csv',encoding='utf-8')
df_1398 = pd.read_csv('601398.csv',encoding='utf-8')
df_050 = pd.read_csv('600050.csv',encoding='utf-8')
df_000 = pd.read_csv('600000.csv',encoding='utf-8')
df_004['ret_004'] = df_004['closePrice'].pct_change()
df_004 = df_004.loc[:,['tradeDate','ret_004']]
df_015['ret_015'] = df_015['closePrice'].pct_change()
df_015 = df_015.loc[:,['tradeDate','ret_015']]
df_023['ret_023'] = df_023['closePrice'].pct_change()
df_023 = df_023.loc[:,['tradeDate','ret_023']]
df_033['ret_033'] = df_033['closePrice'].pct_change()
df_033 = df_033.loc[:,['tradeDate','ret_033']]
df_343['ret_343'] = df_343['closePrice'].pct_change()
df_343 = df_343.loc[:,['tradeDate','ret_343']]
df_346['ret_346'] = df_346['closePrice'].pct_change()
df_346 = df_346.loc[:,['tradeDate','ret_346']]
df_183['ret_183'] = df_183['closePrice'].pct_change()
df_183 = df_183.loc[:,['tradeDate','ret_183']]
df_1398['ret_1398'] = df_1398['closePrice'].pct_change()
df_1398 = df_1398.loc[:,['tradeDate','ret_1398']]
df_050['ret_050'] = df_050['closePrice'].pct_change()
df_050 = df_050.loc[:,['tradeDate','ret_050']]
df_000['ret_000'] = df_000['closePrice'].pct_change()
df_000 = df_000.loc[:,['tradeDate','ret_000']]
ten_df = pd.merge(df_004,df_015,on='tradeDate')
ten_df = pd.merge(ten_df,df_023,on='tradeDate')
ten_df = pd.merge(ten_df,df_033,on='tradeDate')
ten_df = pd.merge(ten_df,df_343,on='tradeDate')
ten_df = pd.merge(ten_df,df_346,on='tradeDate')
ten_df = pd.merge(ten_df,df_183,on='tradeDate')
ten_df = pd.merge(ten_df,df_1398,on='tradeDate')
ten_df = pd.merge(ten_df,df_050,on='tradeDate')
ten_df = pd.merge(ten_df,df_000,on='tradeDate')
ten_df.dropna(inplace=True)
ten_df['tradeDate'] = pd.to_datetime(ten_df['tradeDate'])
ten_df.set_index('tradeDate',inplace=True)
def annualize_rets(returns,n_periods):
'''
给定一系列的收益率和期数,算出年化收益率
'''
# 每一期的平均收益
r_periodic_mean = ((1+returns).prod())**(1/returns.shape[0])-1
return (1+r_periodic_mean)**n_periods-1
def annualize_std(returns,n_periods):
'''
给定一系列的收益率,算出年化的标准差
'''
return returns.std()*np.sqrt(n_periods)
def portfolio_return(weights,returns):
'''
计算投资组合收益率,weights和returns需要矩阵形式
weights是组合资产的权重
returns是组合中的资产年化收益率
'''
return weights.T @ returns
def portfolio_vol(weights,covmat):
'''
计算投资组合风险(波动率),weights和covmat需要矩阵形式
covmat代表的是协方差矩阵
'''
return np.sqrt(weights.T @ covmat @ weights)
def get_gmvp(covmat):
'''
寻找全局最小方差点
covmat 代表资产之间的协方差矩阵
'''
from scipy.optimize import minimize
n = covmat.shape[0]
init_guess = np.repeat(1/n,n)
bounds = ((0.0,1.0),)*n #每个资产的权重在0~1之间
weights_sum_to_1 = {'type':'eq','fun': lambda weights:np.sum(weights)-1}
weights = minimize(portfolio_vol,init_guess,args=(covmat,),method='SLSQP',bounds=bounds,constraints=(weights_sum_to_1))
return weights.x
def minimize_vol(target_return,annual_rets,covmat):
'''
最小方差边界函数
target_return 为客户所要求的收益率水平
annual_rets 代表组合中的资产的年化收益率
covmat 代表资产之间的协方差矩阵
'''
from scipy.optimize import minimize
n = annual_rets.shape[0]
init_guess = np.repeat(1/n,n)
bounds = ((0.0,1.0),)*n #每个资产的权重在0~1之间
weights_sum_to_1 = {'type':'eq','fun': lambda weights:np.sum(weights)-1}
return_is_target = {'type':'eq','args':(annual_rets,),'fun': lambda weights,annual_rets: portfolio_return(weights,annual_rets)-target_return}
weights = minimize(portfolio_vol,init_guess,args=(covmat,),method='SLSQP',bounds=bounds,constraints=(weights_sum_to_1,return_is_target))
return weights.x
def var_historic(r,level=5):
'''
给定一个DataFrame或者Series,计算VaR
注意:5%的显著性水平要写成5,而不是0.05
'''
if isinstance(r,pd.Series):
return abs(np.percentile(r,level))
elif isinstance(r,pd.DataFrame):
return r.aggregate(var_historic,level=level)
else:
raise TypeError('收益率必须为DataFrame或Series')
def drawdown(return_series:pd.Series):
'''
把一个时间序列做成最大回撤的表格
表格字段为:
财富指数
上一个最大值
回撤率
'''
wealth = 1*(1+return_series).cumprod()
previos_max = wealth.cummax()
drawdowns = (wealth-previos_max)/previos_max
return pd.DataFrame({'wealth':wealth,
'previos_max':previos_max,
'drawdowns':drawdowns})
该产品选择了10个标的,计算这10个标的各自的年化收益率和年化协方差
er_009 = annualize_rets(ten_df,252)
cov_009 = np.cov(ten_df,rowvar=False)*252
检查该产品的gmvp的收益率是否小于指定的收益率0.09,成立,则该产品有效
gmvp_10samples_weights = get_gmvp(cov_009)
gmvp_10samples_ret = portfolio_return(gmvp_10samples_weights,er_009)
gmvp_10samples_ret
# out: 0.07938558348434649
该产品gmvp的收益率为0.07938558348434649,小于0.09,该产品有效
计算出该产品最优投资组合对应的权重,计算该权重下的年化收益率和年化波动率
fund_009_weights = minimize_vol(0.09,er_009,cov_009)
fund_009_weights
fund_009_ret = portfolio_return(fund_009_weights,er_009)
fund_009_vol = portfolio_vol(fund_009_weights,cov_009)
fund_009_ret,fund_009_vol
根据各个标的的日收益率历史数据和产品的权重,往回推算出产品的历史日收益率
计算产品的日收益率
daily_ret_fund009 = ten_df@fund_009_weights
daily_ret_fund009
# 历史模拟法计算
VaR_fund009 = var_historic(daily_ret_fund009)
VaR_fund009
根据1962天的历史日数据得出,在95%置信水平下,每天损失不会操作1.6218%,只有5%的概率,该产品损失会超过1.6218%;也可以说在未来100天内,有5天该产品每天损失会超过1.6218%。
到这一步VaR的结果,看客户是否能接受这样的风险,如果不能接受,重新设计产品
res_maxdrawdown = drawdown(daily_ret_fund009)
res_maxdrawdown.min()
该产品最大回撤为32.89%,如果客户无法接受,重新设计产品
# 回撤曲线
res_maxdrawdown.plot(y='drawdowns')
# 夏普比率
rf = 0.0135
sharpe_009 = (fund_009_ret-rf)/fund_009_vol
sharpe_009
# out: 0.4028147123950633
计算无风险资产的日收益率,已知的国债收益率0.0135是年化收益率,要从年化收益率反推出日收益率
# 计算无风险资产的日收益率
rf_daily = (1+rf)**(1/252)-1
rf_daily
# out: 5.321445913253342e-05
获取沪深300指数的历史日收益率
hs300_df = pd.read_csv('index_hs300.csv',encoding='utf-8')
hs300_df['ret_hs300'] = hs300_df['closeIndex'].pct_change()
hs300_df['tradeDate'] = pd.to_datetime(hs300_df['tradeDate'])
hs300_df = hs300_df.loc[:,['tradeDate','ret_hs300']]
hs300_df.set_index('tradeDate',inplace=True)
hs300_df.dropna(inplace=True)
ten_hs300_df = pd.merge(ten_df,hs300_df,on='tradeDate')
ten_hs300_df.head()
market_return_daily = ten_hs300_df['ret_hs300']
# 产品的扣除无风险收益后的收益
excess_ret_fund009 = daily_ret_fund009-rf_daily
# 沪深300扣除无风险收益后的收益
excess_ret_market = market_return_daily-rf_daily
# 给市场组合超额收益加一列1
excess_ret_market = pd.DataFrame(excess_ret_market)
excess_ret_market['Constant'] = 1
# 对市场组合超额收益和产品超额收益做线性回归,寻找alpha和beta
import statsmodels.api as stm
lr = stm.OLS(excess_ret_fund009,excess_ret_market).fit()
lr.summary()
取出Beta和Alpha
beta = lr.params[0]
alpha = lr.params[1]
beta,alpha
# out: (0.6575807102116948, 0.00018512144578591218)
计算年化Alpha
# 计算年化Alpha
annual_alpha = (1+alpha)**252-1
annual_alpha
# out: 0.047751340108930895
# 计算特雷诺比率
treynor_009 = (fund_009_ret-rf)/beta
treynor_009
# out: 0.11633552933127686
# 计算009产品的财富指数
fund_009_wealth = 1*(1+daily_ret_fund009).cumprod()
benchmarket_wealth = 1*(1+market_return_daily).cumprod()
df = pd.DataFrame({'fund_009_wealth':fund_009_wealth,'benchmarket_wealth':benchmarket_wealth})
df.plot(figsize=(8,6))
链接:https://pan.baidu.com/s/1Y0aGIbpRdSs2waz_yF008A
提取码:101n