Пример #1
0
def effrontier(mu, S, sht, nameplot):
    cla = CLA(mu, S)
    fig = plt.figure(figsize=(8, 8))
    cla.max_sharpe()
    ax = cla.plot_efficient_frontier(showfig=False)
    fig = ax.get_figure()
    sht.pictures.add(fig, name=nameplot, update=True)
Пример #2
0
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
Пример #3
0
def plot_stock_insights(stock_price, Portfolio):
    mu = expected_returns.mean_historical_return(stock_price)
    S = risk_models.sample_cov(stock_price)
    ef = EfficientFrontier(mu, S)
    cleaned_weights = ef.clean_weights()
    cla = CLA(mu, S)
    plotting.plot_efficient_frontier(cla)
    plotting.plot_covariance(S)
    plotting.plot_weights(cleaned_weights)
Пример #4
0
def test_ef_plot():
    df = get_data()
    rets = expected_returns.mean_historical_return(df)
    S = risk_models.exp_cov(df)
    cla = CLA(rets, S)

    ax = Plotting.plot_efficient_frontier(cla, showfig=False)
    assert len(ax.findobj()) == 137
    ax = Plotting.plot_efficient_frontier(cla,
                                          show_assets=False,
                                          showfig=False)
    assert len(ax.findobj()) == 149
Пример #5
0
def test_cla_plot_ax():
    plt.figure()
    df = get_data()
    rets = expected_returns.mean_historical_return(df)
    S = risk_models.exp_cov(df)
    cla = CLA(rets, S)

    fig, ax = plt.subplots(figsize=(12, 10))
    plotting.plot_efficient_frontier(cla, ax=ax)
    assert len(ax.findobj()) == 143
    plt.close()
    plt.close()
Пример #6
0
    def plot_stock_insights(self, scatter=False):

        ef = EfficientFrontier(self.mu, self.S)
        weights = ef.max_sharpe()
        cleaned_weights = ef.clean_weights()
        cla = CLA(self.mu, self.S)
        try:
            eff_front = plotting.plot_efficient_frontier(cla)
            eff_front.tick_params(axis='both', which='major', labelsize=5)
            eff_front.tick_params(axis='both', which='minor', labelsize=5)
            eff_front.get_figure().savefig(os.path.join(
                self.output_path, "efficient_frontier.png"),
                                           dpi=300)
        except:
            print("Failed to plot efficient frontier")
        cov = plotting.plot_covariance(self.S)
        weights_bar = plotting.plot_weights(cleaned_weights)
        if self.save_output:
            cov.tick_params(axis='both', which='major', labelsize=5)
            cov.tick_params(axis='both', which='minor', labelsize=5)
            cov.get_figure().savefig(os.path.join(self.output_path,
                                                  "cov_matrix.png"),
                                     dpi=300)
            weights_bar.tick_params(axis='both', which='major', labelsize=5)
            weights_bar.tick_params(axis='both', which='minor', labelsize=5)
            weights_bar.get_figure().savefig(os.path.join(
                self.output_path, "weights_bar.png"),
                                             dpi=300)

        retscomp = self.stock_prices.pct_change()
        corrMatrix = retscomp.corr()
        corr_heat = sns.heatmap(corrMatrix, xticklabels=True, yticklabels=True)
        plt.title("Corr heatmap")
        if self.save_output:
            corr_heat.tick_params(axis='both', which='major', labelsize=5)
            corr_heat.tick_params(axis='both', which='minor', labelsize=5)
            fig = corr_heat.get_figure()
            fig.figsize = (10, 10)
            fig.savefig(os.path.join(self.output_path, "corr_heatmap.png"),
                        dpi=300)
        plt.show()
        if scatter:
            plt.figure()
            plt.title("Corr scatter")
            self.scattermat = pd.plotting.scatter_matrix(retscomp,
                                                         diagonal='kde',
                                                         figsize=(10, 10))

            if self.save_output:
                plt.savefig(os.path.join(self.output_path, "corr_scatter.png"),
                            dpi=300)
            plt.show()
Пример #7
0
def test_cla_plot():
    plt.figure()
    df = get_data()
    rets = expected_returns.mean_historical_return(df)
    S = risk_models.exp_cov(df)
    cla = CLA(rets, S)

    ax = plotting.plot_efficient_frontier(cla, showfig=False)
    assert len(ax.findobj()) == 143
    plt.clf()

    ax = plotting.plot_efficient_frontier(cla, show_assets=False, showfig=False)
    assert len(ax.findobj()) == 161
    plt.clf()
    plt.close()
# In[264]:

e_cov_during = np.array(CovarianceShrinkage(df7).ledoit_wolf())

# 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')
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)
Пример #10
0
 'GM': 0.05557666024185722,
 'GOOG': 0.049560084289929286,
 'JPM': 0.017675709092515708,
 'MA': 0.03812737349732021,
 'PFE': 0.07786528342813454,
 'RRC': 0.03161528695094597,
 'SBUX': 0.039844436656239136,
 'SHLD': 0.027113184241298865,
 'T': 0.11138956508836476,
 'UAA': 0.02711590957075009,
 'WMT': 0.10569551148587905,
 'XOM': 0.11175337115721229}
"""

# Crticial Line Algorithm
cla = CLA(mu, S)
print(cla.max_sharpe())
cla.portfolio_performance(verbose=True)
plotting.plot_efficient_frontier(cla)  # to plot
"""
{'GOOG': 0.020889868669945022,
 'AAPL': 0.08867994115132602,
 'FB': 0.19417572932251745,
 'BABA': 0.10492386821217001,
 'AMZN': 0.0644908140418782,
 'GE': 0.0,
 'AMD': 0.0,
 'WMT': 0.0034898157701416382,
 'BAC': 0.0,
 'GM': 0.0,
 'T': 2.4138966206946562e-19,
Пример #11
0
 'GOOG': 0.049560084289929286,
 'JPM': 0.017675709092515708,
 'MA': 0.03812737349732021,
 'PFE': 0.07786528342813454,
 'RRC': 0.03161528695094597,
 'SBUX': 0.039844436656239136,
 'SHLD': 0.027113184241298865,
 'T': 0.11138956508836476,
 'UAA': 0.02711590957075009,
 'WMT': 0.10569551148587905,
 'XOM': 0.11175337115721229}
"""


# Crticial Line Algorithm
cla = CLA(mu, S)
print(cla.max_sharpe())
cla.portfolio_performance(verbose=True)
cla.plot_efficient_frontier()  # to plot

"""
{'GOOG': 0.020889868669945022,
 'AAPL': 0.08867994115132602,
 'FB': 0.19417572932251745,
 'BABA': 0.10492386821217001,
 'AMZN': 0.0644908140418782,
 'GE': 0.0,
 'AMD': 0.0,
 'WMT': 0.0034898157701416382,
 'BAC': 0.0,
 'GM': 0.0,
plt.show(piechart)

#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
Пример #13
0
# df = pd.read_csv("tests/resources/stock_prices.csv", parse_dates=True, index_col="date")
df = pd.read_csv(os.path.join(path, 'stock_prices.csv'),
                 parse_dates=True,
                 index_col="Date")

returns = df.pct_change().dropna()
# Calculate expected returns and sample covariance
mu = expected_returns.mean_historical_return(df)
S = risk_models.sample_cov(df)

# Optimise for maximal Sharpe ratio
ef = EfficientFrontier(mu, S)
raw_weights = ef.max_sharpe()
cleaned_weights = ef.clean_weights()
ef.save_weights_to_file("weights.csv")  # saves to file
print(cleaned_weights)
ef.portfolio_performance(verbose=True)

latest_prices = get_latest_prices(df)

da = DiscreteAllocation(cleaned_weights,
                        latest_prices,
                        total_portfolio_value=600)
allocation, leftover = da.lp_portfolio()
print("Discrete allocation:", allocation)
print("Funds remaining: ${:.2f}".format(leftover))
cla = CLA(mu, S)
plotting.plot_efficient_frontier(cla)
plotting.plot_covariance(S)
plotting.plot_weights(cleaned_weights)