def target_opt(df_daily_returns, target_ret=None): #********* Markowitz Portfolio with target return ************************ cov_mat = df_daily_returns.cov() avg_rets = df_daily_returns.mean() if target_ret == None: target_ret = avg_rets.quantile(0.7) weights = pfopt.markowitz_portfolio( cov_mat, avg_rets, target_ret) # returns a df series of weights weights = pfopt.truncate_weights(weights) # Truncate some tiny weights weights = weights[weights != 0] # remove any weights of 0 weights = weights.round( decimals=4) # clean up weight values by rounding ret = (weights * avg_rets).sum() # float of the portfolio average daily return # p = np.asmatrix(avg_rets) # this is where the error is occurring # w = np.asmatrix(weights) # C = np.asmatrix(np.cov(df_daily_returns)) # sigma = np.sqrt(w * C * w.T) #standard deviation #*********************************************************************************************** # C is covariance matrix of the returns NOTE: if it used the simple std dev std(array(ret_vec).T*w) # the result would be slightly different as it would not take covariances into account.! std = (weights * df_daily_returns ).sum(1).std() # float of the portfolio standard deviation return weights, ret, std
def test_truncate(self): raw_weights = pd.Series([0.5, 0.4, 0.01, 0.09], index=['a', 'b', 'c', 'd']) adj_weights = pfopt.truncate_weights(raw_weights, min_weight=0.05, rescale=False) exp_weights = raw_weights[:] exp_weights['c'] = 0.0 self.assertTrue((adj_weights == exp_weights).all())
def test_rescale(self): raw_weights = pd.Series([0.5, 0.4, 0.01, 0.8], index=['a', 'b', 'c', 'd']) adj_weights = pfopt.truncate_weights(raw_weights, min_weight=0.0, rescale=True) self.assertTrue(np.isclose(adj_weights.sum(), 1.0))
def get_b(self, data, last_b): x = data x_mean = np.mean(x) lam = max(0., (self.eps - np.dot(last_b, x)) / norm(x - x_mean) **2) lam = min(1e+5, lam) b = last_b + lam * (x - x_mean) b = np.log(1. + np.exp(b)) b = b / b.sum() b = pfopt.truncate_weights(b) return b
def main(): returns, cov_mat, avg_rets = pfopt.create_test_data() section("Example returns") print(returns.head(10)) print("...") section("Average returns") print(avg_rets) section("Covariance matrix") print(cov_mat) section("Minimum variance portfolio (long only)") weights = pfopt.min_var_portfolio(cov_mat) print_portfolio_info(returns, avg_rets, weights) section("Minimum variance portfolio (long/short)") weights = pfopt.min_var_portfolio(cov_mat, allow_short=True) print_portfolio_info(returns, avg_rets, weights) # Define some target return, here the 70% quantile of the average returns target_ret = avg_rets.quantile(0.7) section("Markowitz portfolio (long only, target return: {:.5f})".format( target_ret)) weights = pfopt.markowitz_portfolio(cov_mat, avg_rets, target_ret) print_portfolio_info(returns, avg_rets, weights) section("Markowitz portfolio (long/short, target return: {:.5f})".format( target_ret)) weights = pfopt.markowitz_portfolio(cov_mat, avg_rets, target_ret, allow_short=True) print_portfolio_info(returns, avg_rets, weights) section( "Markowitz portfolio (market neutral, target return: {:.5f})".format( target_ret)) weights = pfopt.markowitz_portfolio(cov_mat, avg_rets, target_ret, allow_short=True, market_neutral=True) print_portfolio_info(returns, avg_rets, weights) section("Tangency portfolio (long only)") weights = pfopt.tangency_portfolio(cov_mat, avg_rets) weights = pfopt.truncate_weights(weights) # Truncate some tiny weights print_portfolio_info(returns, avg_rets, weights) section("Tangency portfolio (long/short)") weights = pfopt.tangency_portfolio(cov_mat, avg_rets, allow_short=True) print_portfolio_info(returns, avg_rets, weights)
def main(): # returns, cov_mat, avg_rets = pfopt.create_test_data(num_days=1000) returns, cov_mat, avg_rets = load_data() # yy = returns['asset_a'] # xx = [ii for ii in range(len(yy))] # plt.plot(xx, yy) # plt.hlines(avg_rets[0], xmin=0, xmax=100, colors='black') # plt.show() # return 0 section("Example returns") print(returns.head(5)) print("...") section("Average returns") print(avg_rets) section("Covariance matrix") print(cov_mat) section("Minimum variance portfolio (long only)") weights = pfopt.min_var_portfolio(cov_mat) print_portfolio_info(returns, avg_rets, weights) section("Minimum variance portfolio (long/short)") weights = pfopt.min_var_portfolio(cov_mat, allow_short=True) print_portfolio_info(returns, avg_rets, weights) # Define some target return, here the 70% quantile of the average returns target_ret = avg_rets.quantile(0.7) section("Markowitz portfolio (long only, target return: {:.5f})".format(target_ret)) weights = pfopt.markowitz_portfolio(cov_mat, avg_rets, target_ret) print_portfolio_info(returns, avg_rets, weights) section("Markowitz portfolio (long/short, target return: {:.5f})".format(target_ret)) weights = pfopt.markowitz_portfolio(cov_mat, avg_rets, target_ret, allow_short=True) print_portfolio_info(returns, avg_rets, weights) section("Markowitz portfolio (market neutral, target return: {:.5f})".format(target_ret)) weights = pfopt.markowitz_portfolio(cov_mat, avg_rets, target_ret, allow_short=True, market_neutral=True) print_portfolio_info(returns, avg_rets, weights) section("Tangency portfolio (long only)") weights = pfopt.tangency_portfolio(cov_mat, avg_rets) weights = pfopt.truncate_weights(weights) # Truncate some tiny weights print_portfolio_info(returns, avg_rets, weights) section("Tangency portfolio (long/short)") weights = pfopt.tangency_portfolio(cov_mat, avg_rets, allow_short=True) print_portfolio_info(returns, avg_rets, weights)
def tangency_opt(df_daily_returns): cov_mat = df_daily_returns.cov() avg_rets = df_daily_returns.mean() weights = pfopt.tangency_portfolio(cov_mat, avg_rets) weights = pfopt.truncate_weights(weights) # Truncate some tiny weights weights = weights[weights != 0] weights = weights.round(decimals=4) ret = (weights * avg_rets).sum() ret = ret.round(decimals=4) std = (weights * df_daily_returns).sum(1).std() std = std.round(decimals=4) return weights, ret, std
def min_variance(df_daily_returns): #***************** Minimum variance portfolio *********************** cov_mat = df_daily_returns.cov() avg_rets = df_daily_returns.mean() weights = pfopt.min_var_portfolio(cov_mat) weights = pfopt.truncate_weights(weights) # Truncate some tiny weights weights = weights[weights != 0] weights = weights.round(decimals=4) ret = (weights * avg_rets).sum() ret = ret.round(decimals=4) std = (weights * df_daily_returns).sum(1).std() std = std.round(decimals=4) return weights, ret, std
def main(): returns, cov_mat, avg_rets = pfopt.create_test_data() section("Example returns") print(returns.head(10)) print("...") section("Average returns") print(avg_rets) section("Covariance matrix") print(cov_mat) section("Minimum variance portfolio (long only)") weights = pfopt.min_var_portfolio(cov_mat) print_portfolio_info(returns, avg_rets, weights) section("Minimum variance portfolio (long/short)") weights = pfopt.min_var_portfolio(cov_mat, allow_short=True) print_portfolio_info(returns, avg_rets, weights) # Define some target return, here the 70% quantile of the average returns target_ret = avg_rets.quantile(0.7) section("Markowitz portfolio (long only, target return: {:.5f})".format(target_ret)) weights = pfopt.markowitz_portfolio(cov_mat, avg_rets, target_ret) print_portfolio_info(returns, avg_rets, weights) section("Markowitz portfolio (long/short, target return: {:.5f})".format(target_ret)) weights = pfopt.markowitz_portfolio(cov_mat, avg_rets, target_ret, allow_short=True) print_portfolio_info(returns, avg_rets, weights) section("Markowitz portfolio (market neutral, target return: {:.5f})".format(target_ret)) weights = pfopt.markowitz_portfolio(cov_mat, avg_rets, target_ret, allow_short=True, market_neutral=True) print_portfolio_info(returns, avg_rets, weights) section("Tangency portfolio (long only)") weights = pfopt.tangency_portfolio(cov_mat, avg_rets) weights = pfopt.truncate_weights(weights) # Truncate some tiny weights print_portfolio_info(returns, avg_rets, weights) section("Tangency portfolio (long/short)") weights = pfopt.tangency_portfolio(cov_mat, avg_rets, allow_short=True) print_portfolio_info(returns, avg_rets, weights)
print('-' * len(caption)) def print_portfolio_info(returns, avg_rets, weights): """ Print information on expected portfolio performance. """ ret = (weights * avg_rets).sum() std = (weights * returns).sum(1).std() sharpe = ret / std print("Optimal weights:\n{}\n".format(weights)) print("Expected return: {}".format(ret)) print("Expected variance: {}".format(std**2)) print("Expected Sharpe: {}".format(sharpe)) # Define some target return, here the 70% quantile of the average returns target_ret = avg_rets.quantile(0.9) weights = pfopt.min_var_portfolio(cov_mat) print_portfolio_info(returns, avg_rets, weights) section("Markowitz portfolio (long only, target return: {:.5f})".format( target_ret)) weights = pfopt.markowitz_portfolio(cov_mat, avg_rets, target_ret) print_portfolio_info(returns, avg_rets, weights) section("Tangency portfolio (long only)") weights = pfopt.tangency_portfolio(cov_mat, avg_rets) weights = pfopt.truncate_weights(weights) # Truncate some tiny weights print_portfolio_info(returns, avg_rets, weights)
market_neutral=False) #需输入协方差矩阵cov_mat,年预期收益exp_rets,0.2代表想要的年收益,allow_short表示是否允许做空,market_neutral表示是否具有市场中性 print(portfolio_1) #得到的结果表示若要实现0.2的年收益,则分别需买入这些股票的比重分别为 #计算最小方差的权重 (opt.min_var_portfolio) portfolio_mv = opt.min_var_portfolio(cov_mat, allow_short=False) print(portfolio_mv) #计算最优组合的权重 (opt.tangency_portfolio) (夏普比率最高的比重) portfolio_tp = opt.tangency_portfolio( cov_mat, exp_rets, allow_short=False) #需输入协方差矩阵cov_mat,年预期收益exp_rets print(portfolio_tp) #去除少于0.01权重的股票,低于0.01权重的不建议购买 weigth_t = opt.truncate_weights(portfolio_tp, min_weight=0.01, rescale=True) print(weigth_t) #计算组合风险 import numpy as np Portfolio_v = np.dot(weigth_t.T, np.dot(cov_mat, weigth_t)) #weigth_t.T表示weigth_t的转置,cov_mat是协方差矩阵 P_sigma = np.sqrt(Portfolio_v) #开方求标准差 P_sigma #Markowitz可视化 (求最高夏普比率) ??? import matplotlib.pyplot as plt port_returns = [] port_variance = [] for p in range(4000): #随机4000个值