Python

profileyiyi0023
Cameron-plotting-functions.txt

def random_weights(n, bounds=(0., 1.), total=1.0): ''' This function generates random weights. You should not need to edit this function. ''' low = bounds[0] high = bounds[1] if high < low: raise ValueError('Higher bound must be greater or ' 'equal to lower bound') if n * high < total or n * low > total: raise ValueError('solution not possible with given n and bounds') w = [0] * n tgt = -float(total) for i in range(n): rn = n - i - 1 rhigh = rn * high rlow = rn * low lowb = max(-rhigh - tgt, low) highb = min(-rlow - tgt, high) rw = random.uniform(lowb, highb) w[i] = rw tgt += rw random.shuffle(w) return w def random_portfolio(exp_rets, covar, bounds): ''' This function creates a random portfolio using a collection of average returns, a covariance matrix, and a set of bounds which asset weights are constrained between. ''' # Calculate a set of random weights. weights = random_weights(len(exp_rets), bounds) # Calculate the portfolio's return using the # random weights. mean = sum(exp_rets * weights) # Calculate the portfolio's standard deviation # using the random weights. var = np.dot(np.dot(weights, covar), weights) ** (1./2.) return mean, var, weights def plot_frontier(ef, mu, S, rf, num_points=200, num_random=100, market_neutral=False): # 'targets' contains all the returns we want # to estimate. targets = np.linspace(0, 0.25, num_points) # The variables store the efficient frontier # portfolio returns and volatilities. returns = [] vols = [] # Variables to store random portfolio returns # and volatilities. random_returns = [] random_vols = [] ef.weights = None # Generate frontier portfolios. for i in range(0, num_points): # Find a portfolio that has the minimum variance for the target return. ef.efficient_return(targets[i], market_neutral) # Generate the frontier return and volatility. ret, vol, _ = ef.portfolio_performance(verbose = False, risk_free_rate = rf) # Store the returns and volatilities. vols.append(vol) returns.append(ret) # Clear the stored weights. ef.weights = None # Generate all the random portoflios. for i in range(0, num_random): # Generate a random portfolio. rret, rvol, _ = random_portfolio(mu, S, (-1.0, 1.0)) # Store the returns and volatilities. random_returns.append(rret) random_vols.append(rvol) # Retrieve the tangent portfolio's returns # and volatility. ef.max_sharpe(rf) tangent_return, tangent_vol, _ = ef.portfolio_performance( risk_free_rate = rf, verbose = False) # Calculate the tangent portfolio's sharpe ratio. tangent_sharpe = (tangent_return-rf)/tangent_vol # Make the Capital Market Line. tangency_points = np.linspace(0, 0.2, num_points) tangency_line = rf + (tangency_points * tangent_sharpe) # Create a plot. fig, ax = plt.subplots(figsize=(12, 4)) # Add the series. ax.plot(vols, returns, label = "Efficient Frontier") ax.plot(tangency_points, tangency_line, label = "Capital Market Line") ax.plot(tangent_vol, tangent_return, 'go', label = "Tangency Portfolio") ax.plot(random_vols, random_returns, 'bx', label = "Random Portfolio", alpha = 0.2) # Plot the basis assets as red dots. for i in mu.index: i_sd = S.loc[i, i] ** (1./2.) i_mu = mu.loc[i] ax.plot(i_sd, i_mu, 'ro', mu.loc[i]) # Label the axes. plt.xlabel("s") plt.ylabel("Return") # Rescale the axes. ax.set_xlim(0.0, 0.3) ax.set_ylim(0.0, 0.3) # Set axes to percentages. vals = ax.get_yticks() ax.set_yticklabels(['{:,.2%}'.format(x) for x in vals]) vals = ax.get_xticks() ax.set_xticklabels(['{:,.2%}'.format(x) for x in vals]) # Additional plotting features. plt.legend() plt.grid() # Uncomment the below line if you want to save your graphs. # fig.savefig("frontier.png") plt.show() return # End of function definition.