import numpy as np
import pandas as pd
import edhec_risk_kit as erk
import matplotlib.pyplot as plt
%matplotlib inline
cols = ['Fin', 'Util', 'Telcm', 'Hlth']
ind = erk.get_ind_returns().loc['1980':'2015', cols]
Calculate the portfolio weight for each asset
er = erk.annualize_rets(ind, periods_per_year=12)
cov = ind.cov()
w_msr = erk.msr(riskfree_rate=0.02, er=er, cov=cov)
pd.DataFrame(w_msr, index=cols, columns=['Shape Ratio Weight'])
Calculate the portfolio weight for each asset
w_gmv = erk.gmv(cov=cov)
pd.DataFrame(w_gmv, index=cols, columns=['GMV Weight'])
ind = erk.get_ind_returns().loc[:, cols]
er = erk.annualize_rets(
ind['1980':'2015'],
periods_per_year=12
)
cov = ind['1980':'2015'].cov()
w_msr = erk.msr(riskfree_rate=0.02, er=er, cov=cov)
w_gmv = erk.gmv(cov=cov)
vol_msr = np.sqrt(12)*erk.portfolio_vol(
weights=w_msr,
covmat=ind['2016':'2018'].cov()
)
vol_gmv = np.sqrt(12)*erk.portfolio_vol(
weights=w_gmv,
covmat=ind['2016':'2018'].cov()
)
print('MSR 2016-2018 variance:', vol_msr)
print('GMV 2016-2018 variance:', vol_gmv)
r = erk.annualize_rets(
ind['2016':'2018'],
periods_per_year=12
)
r_msr = erk.portfolio_return(
weights = w_msr,
returns = r
)
r_gmv = erk.portfolio_return(
weights = w_gmv,
returns = r
)
print('MSR 2016-2018 return:', r_msr)
print('GMV 2016-2018 return:', r_gmv)
Plot the efficient frontier for a portfolio considering 2 assets, Finance and Utilities stocks, based on evaluation from 1980 to 2015
er = erk.annualize_rets(
ind['1980':'2015'],
periods_per_year=12
)
erk.plot_ef2(
100,
er=er[['Fin', 'Util']],
cov=ind.loc['1980':'2015', ['Fin', 'Util']].cov()
)
er = erk.annualize_rets(
ind['1980':'2015'],
periods_per_year=12
)
erk.plot_ef(
300,
er=er,
cov=ind.loc['1980':'2015', cols].cov(),
show_ew=True,
show_gmv=True
)
Considering the industries in the 30 industry returns data from 1960 to 2015, calculating the asset weights that minimize volatility which achieving a target return of 12%
ind = erk.get_ind_returns(n_inds=30)
er = erk.annualize_rets(
ind['1960':'2015'],
periods_per_year=12
)
weights = erk.minimize_vol(
target_return=0.12,
er=er,
cov=ind['1960':'2015'].cov()
)
weights_df = pd.DataFrame(weights, index=ind.columns, columns=['Weights'])
weights_df.sort_values('Weights', ascending=False).plot.bar()