Exemple #1
0
def get_portfolio(expected_returns, risk_array):
    cv = covariance_matrix(risk_array)
    ef = EfficientFrontier(expected_returns, cv)
    raw_weights = ef.max_sharpe()
    cleaned_weights = ef.clean_weights()
    print(cleaned_weights)
    ef.portfolio_performance(verbose=True)
Exemple #2
0
def getMinVolatilityPortfolio(data):
    mu, Sigma = getMuSigma(data)
    ef = EfficientFrontier(mu, Sigma)
    raw_weights = ef.min_volatility()
    weights = ef.clean_weights()
    performance = ef.portfolio_performance()
    return weights, performance
Exemple #3
0
def getMaxSharpePortfolio(data):
    mu, Sigma = getMuSigma(data)
    ef = EfficientFrontier(mu, Sigma)
    raw_weights = ef.max_sharpe()
    weights = ef.clean_weights()
    performance = ef.portfolio_performance()
    return weights, performance
def get_portfolio(universe, df_tr, port_value, cutoff, df_m):
    '''create a portfolio using the stocks from the universe and the closing
    prices from df_tr with a given portfolio value and a weight cutoff value
    using the value of a momemntum indicator to limit the quantity of the stocks'''
    df_t = select_columns(df_tr, universe)
    mu = capm_returns(df_t)
    S = CovarianceShrinkage(df_t).ledoit_wolf()
    # Optimize the portfolio for min volatility
    ef = EfficientFrontier(mu, S)  # Use regularization (gamma=1)
    weights = ef.min_volatility()
    #weights = ef.max_sharpe()
    cleaned_weights = ef.clean_weights(cutoff=cutoff)
    # Allocate
    latest_prices = get_latest_prices(df_t)
    da = DiscreteAllocation(cleaned_weights,
                            latest_prices,
                            total_portfolio_value=port_value)
    allocation = da.greedy_portfolio()[0]
    non_trading_cash = da.greedy_portfolio()[1]
    # Put the stocks and the number of shares from the portfolio into a df
    symbol_list = []
    mom = []
    w = []
    num_shares_list = []
    l_price = []
    tot_cash = []
    for symbol, num_shares in allocation.items():
        symbol_list.append(symbol)
        mom.append(df_m[df_m['stock'] == symbol].values[0])
        w.append(round(cleaned_weights[symbol], 4))
        num_shares_list.append(num_shares)
        l_price.append(latest_prices[symbol])
        tot_cash.append(num_shares * latest_prices[symbol])

    df_buy = pd.DataFrame()
    df_buy['stock'] = symbol_list
    df_buy['momentum'] = mom
    df_buy['weights'] = w
    df_buy['shares'] = num_shares_list
    df_buy['price'] = l_price
    df_buy['value'] = tot_cash
    df_buy = df_buy.append(
        {
            'stock': 'CASH',
            'momentum': 0,
            'weights': round(1 - df_buy['weights'].sum(), 4),
            'shares': 1,
            'price': round(non_trading_cash, 2),
            'value': round(non_trading_cash, 2)
        },
        ignore_index=True)
    df_buy = df_buy.set_index('stock')
    return df_buy, non_trading_cash
def test_clean_weights_short():
    ef = setup_efficient_frontier()
    ef = EfficientFrontier(
        *setup_efficient_frontier(data_only=True), weight_bounds=(-1, 1)
    )
    ef.max_sharpe()
    # In practice we would never use such a high cutoff
    number_tiny_weights = sum(np.abs(ef.weights) < 0.05)
    cleaned = ef.clean_weights(cutoff=0.05)
    cleaned_weights = cleaned.values()
    clean_number_tiny_weights = sum(abs(i) < 0.05 for i in cleaned_weights)
    assert clean_number_tiny_weights == number_tiny_weights
    def get_expected_returns(self):
        mu = expected_returns.mean_historical_return(self.df)
        S = risk_models.sample_cov(self.df)

        ef = EfficientFrontier(mu, S)
        weights = ef.max_sharpe()
        cleaned_weights = ef.clean_weights()
        port_performance_percentage = {
            'cleanedWeights': cleaned_weights,
            'portfolioPerformance': ef.portfolio_performance(verbose=True)
        }
        return port_performance_percentage
Exemple #7
0
 def build_portfolio(self, price_pivot, portfolio_total=10000):
     ''' build a portfolio from price data'''
     mu = expected_returns.mean_historical_return(price_pivot)
     shrink = risk_models.CovarianceShrinkage(price_pivot)
     S = shrink.ledoit_wolf()
     ef = EfficientFrontier(mu, S, weight_bounds=(0, 0.2), gamma=0.8)
     weights = ef.max_sharpe()
     weights = ef.clean_weights()
     latest_prices = get_latest_prices(price_pivot)
     weights = {k: v for k, v in weights.items() if weights[k] > 0.0}
     da = DiscreteAllocation(weights, latest_prices, total_portfolio_value=portfolio_total)
     allocation, leftover = da.lp_portfolio()
     # print("Discrete allocation:", allocation)
     return allocation