def cla_min_vol_weights(rets_bl, covar_bl, config): cla = CLA(rets_bl, covar_bl, weight_bounds= \ (config['min_position_size'] ,config['max_position_size'])) cla.min_volatility() weights = cla.clean_weights() weights = pd.DataFrame.from_dict(weights, orient='index') weights.columns = ['CLA Min Vol'] return weights, cla
def omptimizePortCLA(port, weights, start, plot=False, short=False, printBasicStats=True, how='Sharpe'): #Getting Data df = bpf.getData(port, start) #Plotting the portfolio if plot: bpf.plotPort(df, port) if printBasicStats: bpf.basicStats(df, weights) #Optimization for Sharpe using Efficient Frontier if short: bounds = (-1, 1) else: bounds = (0, 1) mu = df.pct_change().mean() * 252 S = risk_models.sample_cov(df) if how == 'Sharpe': # Maximized on Sharpe Ratio cla = CLA( mu, S ) #Here the weight bounds are being used to allow short positions as well weights = cla.max_sharpe() cleaned_weights = dict(cla.clean_weights()) print("Weights of an optimal portfolio maximised on Sharpe Ratio:") print(cleaned_weights) cla.portfolio_performance(verbose=True) bpf.getDiscreteAllocations(df, weights) plot_ef(cla) plotting.plot_weights(weights) elif how == "Vol": # Minimized on Volatility cla = CLA(mu, S) cla.min_volatility() w = dict(cla.clean_weights()) print("Weights of an optimal portfolio minimized on Volatilty (Risk):") print(w) cla.portfolio_performance(verbose=True) bpf.getDiscreteAllocations(df, w) plot_ef(cla) plotting.plot_weights(w)
# In[265]: type(e_cov_during) # In[266]: returns_during = np.array(df6.mean()) # In[267]: efficient_portfolio_during = CLA(returns_during, e_cov_during) # In[268]: print(efficient_portfolio_during.min_volatility()) # In[269]: # Compute the efficient frontier (ret, vol, weights) = efficient_portfolio_during.efficient_frontier() # In[278]: plt.figure(figsize=(20, 12)) plt.xlabel('Standard Deviation/Volatiltiy/Risk') plt.ylabel('Return for period 2007-2008') plt.title('Efficient Frontier during crisis', size=20) plt.plot(vol, ret, c='r') # In[271]:
#we also create a barchart #create barchart barchart = pd.Series( tickers['Weight']).sort_values(ascending=True).plot.barh(figsize=(10, 6)) plt.show(barchart) #covariance heatmap #to get a grasp how our chosen portfolio correlates with each other asset in the portfolio we state a cov heatmap plotting.plot_covariance(cov_matrix_tickers, plot_correlation=True) ##create the Efficient frontier line and visualize it #in order to visualize the efficient frontier from the optimized portfolio, we need to initiate a new built-in method #we use the CLA method, because it is more robust than the default option cla = CLA(mu_target_tickers, cov_matrix_tickers) if risk_tolerance == 'Low': cla.min_volatility() else: cla.max_sharpe() #plot the efficient frontier line ax_portfolio = plotting.plot_efficient_frontier(cla, ef_param='risk', ef_param_range=np.linspace( 0.2, 0.6, 100), points=1000) #initialize Discrete Allocation to get a full picture what you could buy with a given amount #the Discrete Allocation gives you the discrete amount of shares you have to allocate given your available funds from pypfopt import DiscreteAllocation from datetime import datetime from datetime import timedelta