def test_custom_nonconvex_objective_market_neutral_efficient_risk(): # Recreate the market-neutral efficient_risk optimiser using this API target_risk = 0.19 ef = EfficientFrontier(*setup_efficient_frontier(data_only=True), weight_bounds=(-1, 1)) weight_constr = {"type": "eq", "fun": lambda w: np.sum(w)} risk_constr = { "type": "eq", "fun": lambda w: target_risk**2 - np.dot(w.T, np.dot(ef.cov_matrix, w)), } constraints = [weight_constr, risk_constr] ef.nonconvex_objective( lambda w, mu: -w.T.dot(mu), objective_args=(ef.expected_returns), weights_sum_to_one=False, constraints=constraints, ) np.testing.assert_allclose( ef.portfolio_performance(), (0.2591296227818582, target_risk, 1.258574109251818), atol=1e-6, )
def calculEF(dataframe): mu = expected_returns.mean_historical_return(dataframe) S = risk_models.sample_cov(dataframe) ef = EfficientFrontier(mu, S) weights = ef.nonconvex_objective(deviation_risk_parity, ef.cov_matrix) ef.portfolio_performance(verbose=True) return pd.DataFrame([weights])
parse_dates=True, index_col="date") returns = df.pct_change().dropna() mu = expected_returns.mean_historical_return(df) S = risk_models.sample_cov(df) # Now try with a nonconvex objective from Kolm et al (2014) def deviation_risk_parity(w, cov_matrix): diff = w * np.dot(cov_matrix, w) - (w * np.dot(cov_matrix, w)).reshape( -1, 1) return (diff**2).sum().sum() ef = EfficientFrontier(mu, S) weights = ef.nonconvex_objective(deviation_risk_parity, ef.cov_matrix) ef.portfolio_performance(verbose=True) """ Expected annual return: 22.9% Annual volatility: 19.2% Sharpe Ratio: 1.09 """ # Black-Litterman spy_prices = pd.read_csv("tests/spy_prices.csv", parse_dates=True, index_col=0, squeeze=True) delta = black_litterman.market_implied_risk_aversion(spy_prices) mcaps = {