def ef_risk_strategy(returns=None, cov_matrix=None, target_volatility=5.0): assert returns is not None assert cov_matrix is not None ef = EfficientFrontier(returns, cov_matrix) ef.add_objective(objective_functions.L2_reg, gamma=0.1) weights = ef.efficient_risk(target_volatility=target_volatility) return weights, portfolio_performance(ef), ef
def test_weight_bounds_minus_one_to_one(): ef = EfficientFrontier(*setup_efficient_frontier(data_only=True), weight_bounds=(-1, 1)) assert ef.max_sharpe() assert ef.min_volatility() assert ef.efficient_return(0.05) assert ef.efficient_risk(0.05)
def test_efficient_risk_exp_cov_market_neutral(): df = get_data() ef = EfficientFrontier(*setup_efficient_frontier(data_only=True), weight_bounds=(-1, 1)) ef.cov_matrix = risk_models.exp_cov(df) w = ef.efficient_risk(0.19, market_neutral=True) assert isinstance(w, dict) assert set(w.keys()) == set(ef.tickers) assert set(w.keys()) == set(ef.expected_returns.index) np.testing.assert_almost_equal(ef.weights.sum(), 0) assert (ef.weights < 1).all() and (ef.weights > -1).all() np.testing.assert_allclose(ef.portfolio_performance(), (0.39089308906686077, 0.19, 1.9520670176494717), atol=1e-6)
def test_efficient_risk_market_neutral(): ef = EfficientFrontier(*setup_efficient_frontier(data_only=True), weight_bounds=(-1, 1)) w = ef.efficient_risk(0.19, market_neutral=True) assert isinstance(w, dict) assert set(w.keys()) == set(ef.tickers) assert set(w.keys()) == set(ef.expected_returns.index) np.testing.assert_almost_equal(ef.weights.sum(), 0) assert (ef.weights < 1).all() and (ef.weights > -1).all() np.testing.assert_allclose(ef.portfolio_performance(), (0.2309497469633197, 0.19, 1.1102605909328953), atol=1e-6) sharpe = ef.portfolio_performance()[2] ef_long_only = setup_efficient_frontier() ef_long_only.efficient_return(0.25) long_only_sharpe = ef_long_only.portfolio_performance()[2] assert long_only_sharpe > sharpe
def calculate_optimized_portfolio( tickers: Tuple[str], strategy: str, expected_return: str, risk_model: str, portfolio_value: float, risk_free: float, risk_aversion: float, target_risk: float, target_return: float, tiingo_api_key: Optional[str], verbose: bool, ) -> None: tiingo_api_key = tiingo_api_key or os.environ.get("TIINGO_API_KEY") if tiingo_api_key is None: raise RuntimeError( "Tiingo API key not found. Please pass in an api key or set the " "TIINGO_API_KEY environment variable") stock_data = get_stock_data(tickers, tiingo_api_key) expected_returns = EXPECTED_RETURN_METHODOLOGY[expected_return](stock_data) cov_matrix = RISK_MODELS[risk_model](stock_data) efficient_frontier = EfficientFrontier(expected_returns, cov_matrix) if strategy == "max_sharpe": raw_weights = efficient_frontier.max_sharpe(risk_free_rate=risk_free) elif strategy == "min_vol": raw_weights = efficient_frontier.min_volatility() elif strategy == "eff_risk": raw_weights = efficient_frontier.efficient_risk( target_risk=target_risk, risk_free_rate=risk_free) elif strategy == "eff_return": raw_weights = efficient_frontier.efficient_return( target_return=target_return) cleaned_weights = efficient_frontier.clean_weights() click.echo(cleaned_weights) latest_prices = get_latest_prices(stock_data) discrete_weights = DiscreteAllocation(cleaned_weights, latest_prices, portfolio_value) discrete_weights.lp_portfolio(verbose=verbose) efficient_frontier.portfolio_performance(verbose=True)
def test_efficient_risk_short(): ef = EfficientFrontier(*setup_efficient_frontier(data_only=True), weight_bounds=(None, None)) w = ef.efficient_risk(0.19) assert isinstance(w, dict) assert set(w.keys()) == set(ef.tickers) assert set(w.keys()) == set(ef.expected_returns.index) np.testing.assert_almost_equal(ef.weights.sum(), 1) np.testing.assert_allclose( ef.portfolio_performance(), (0.30468522897430295, 0.19, 1.4983424153337392), atol=1e-6, ) sharpe = ef.portfolio_performance()[2] ef_long_only = setup_efficient_frontier() ef_long_only.efficient_return(0.25) long_only_sharpe = ef_long_only.portfolio_performance()[2] assert sharpe > long_only_sharpe
def test_efficient_risk_market_neutral(): ef = EfficientFrontier( *setup_efficient_frontier(data_only=True), weight_bounds=(-1, 1) ) w = ef.efficient_risk(0.19, market_neutral=True) assert isinstance(w, dict) assert set(w.keys()) == set(ef.tickers) assert set(w.keys()) == set(ef.expected_returns.index) np.testing.assert_almost_equal(ef.weights.sum(), 0) assert (ef.weights < 1).all() and (ef.weights > -1).all() np.testing.assert_almost_equal( ef.portfolio_performance(), (0.2309497469661495, 0.19000021138101422, 1.1021245569881066) ) sharpe = ef.portfolio_performance()[2] ef_long_only = setup_efficient_frontier() ef_long_only.efficient_return(0.25) long_only_sharpe = ef_long_only.portfolio_performance()[2] assert long_only_sharpe > sharpe
def handle_data(context, data): date = data.today() if date in context.balance_dates: temp = {} for code in context.stocks: history_price = data.history_bars(code, context.expected_return_days, '1d', 'close') if history_price is not None: temp.update({code: history_price}) history_prices = pd.DataFrame(temp) mu = expected_returns.mean_historical_return(history_prices) if context.cov_method == 'sample': S = risk_models.sample_cov(history_prices) elif context.cov_method == 'semi': S = risk_models.semicovariance(history_prices) elif context.cov_method == 'exp_cov': S = risk_models.exp_cov(history_prices) ef = EfficientFrontier(mu, S) if context.opt_criterion == 'max_sharpe': weights = ef.max_sharpe() elif context.opt_criterion == 'efficient_return': weights = ef.efficient_return(context.target_return) elif context.opt_criterion == 'efficient_risk': weights = ef.efficient_risk(context.targe_risk, context.risk_free_rate) elif context.opt_criterion == 'min_volatility': weights = ef.min_volatility() if context.cleaned_weights is True: weights = ef.clean_weights() weight = [] prices = [] for code in context.stocks: weight.append(weights[code]) prices.append(data.latest_price(code, "1d")) data.order_target_percent(context.stocks, weight, prices)
def test_efficient_risk_short(): ef = EfficientFrontier( *setup_efficient_frontier(data_only=True), weight_bounds=(None, None) ) w = ef.efficient_risk(0.19) assert isinstance(w, dict) assert set(w.keys()) == set(ef.tickers) assert set(w.keys()) == set(ef.expected_returns.index) np.testing.assert_almost_equal(ef.weights.sum(), 1) np.testing.assert_allclose( ef.portfolio_performance(), (0.30468522897560224, 0.19, 1.4947624032507056), atol=1e6, ) sharpe = ef.portfolio_performance()[2] ef_long_only = setup_efficient_frontier() ef_long_only.efficient_return(0.25) long_only_sharpe = ef_long_only.portfolio_performance()[2] assert sharpe > long_only_sharpe
def handle_bar(context, api): date = api.now() #if date in context.balance_dates: history_prices = {} for stock in context.stocks: history_price = api.history_bars(stock, context.expected_return_days, '1d', 'close') history_prices.update({stock: history_price}) history_prices = pd.DataFrame(history_prices) mu = expected_returns.mean_historical_return(history_prices) if context.cov_method == 'sample': S = risk_models.sample_cov(history_prices) elif context.cov_method == 'semi': S = risk_models.semicovariance(history_prices) elif context.cov_method == 'exp_cov': S = risk_models.exp_cov(history_prices) ef = EfficientFrontier(mu, S) if context.opt_criterion == 'max_sharpe': weights = ef.max_sharpe() elif context.opt_criterion == 'efficient_return': weights = ef.efficient_return(context.target_return) elif context.opt_criterion == 'efficient_risk': weights = ef.efficient_risk(context.targe_risk, context.risk_free_rate) elif context.opt_criterion == 'min_volatility': weights = ef.min_volatility() if context.cleaned_weights is True: weights = ef.clean_weights() prices = [] weight = [] for stock in context.stocks: weight.append(weights[stock]) prices.append(api.latest_price(stock, "1d")) api.order_target_percent(stocks, weight, prices)
def optimize_efficient_risk(expected_returns_df, cov_matrix, target_risk): EFOptimizer = EfficientFrontier(expected_returns_df, cov_matrix) weights_dict = EFOptimizer.efficient_risk(target_risk) return weights_dict
"PFE": 0.059025401478094965, "JPM": 0.015529411963789761, "SBUX": 0.03711562842076907, } Expected annual return: 22.7% Annual volatility: 12.7% Sharpe Ratio: 1.63 """ # A long/short portfolio maximising return for a target volatility of 10%, # with a shrunk covariance matrix risk model shrink = risk_models.CovarianceShrinkage(df) S = shrink.ledoit_wolf() ef = EfficientFrontier(mu, S, weight_bounds=(-1, 1)) weights = ef.efficient_risk(target_risk=0.10) ef.portfolio_performance(verbose=True) """ Expected annual return: 29.8% Annual volatility: 10.0% Sharpe Ratio: 2.77 """ # A market-neutral Markowitz portfolio finding the minimum volatility # for a target return of 20% ef = EfficientFrontier(mu, S, weight_bounds=(-1, 1)) weights = ef.efficient_return(target_return=0.20, market_neutral=True) ef.portfolio_performance(verbose=True) """
elif 'daily_profit' in tdata.columns and not np.isnan( tdata['daily_profit']).all(): # 日结 data_list.append( (tdata[['daily_profit']] / 10000 + 1).cumprod(axis=1).rename(columns={ 'daily_profit': filename[0:6] }, index=str).astype('float')) else: print("BAD file: " + filename) data = pd.concat(data_list, axis=1) print(data.info()) # efficient frontier mu = expected_returns.ema_historical_return(data) print(np.isnan(mu).any()) S = risk_models.CovarianceShrinkage(data).ledoit_wolf() print(np.isnan(S).any().any()) ef = EfficientFrontier(mu, S) if args.volatility < 0: print(ef.max_sharpe(args.risk_free_rate)) else: print(ef.efficient_risk(args.volatility, args.risk_free_rate)) ef.portfolio_performance(True) print(str(time() - start) + " s")
[cluster_data_lists[i][asset_name].fillna(cluster_data_lists[i][asset_name].mean()) * w for asset_name, w in weight_list[i].items()]) for i in range(len(cluster_data_lists))], axis=1) new_cov = risk_models.CovarianceShrinkage(new_data).ledoit_wolf() # print(new_mu) # print(new_cov) total_ef = EfficientFrontier(new_mu, new_cov) if args.volatility < 0: cluster_weight = total_ef.max_sharpe(args.risk_free_rate) else: cluster_weight = total_ef.efficient_risk(args.volatility, args.risk_free_rate) total_weight = {} for cluster_id, weights in enumerate(weight_list): for asset_id, w in weights.items(): total_weight[asset_id] = cluster_weight[cluster_id] * w print(len(total_weight)) final_ef = EfficientFrontier(mu, cov) final_ef.weights = total_weight print(total_weight) final_ef.portfolio_performance(True) print(str(time() - start) + " s")
from pypfopt import risk_models from pypfopt import expected_returns from pypfopt.efficient_frontier import EfficientFrontier from pypfopt.black_litterman import BlackLittermanModel prbr = pd.read_excel(r'C:\Users\Jhona\OneDrive\Área de Trabalho\PRBR11.xlsx', index_col='Data', parse_dates=['Data']) ###Expectativa de retornos de mu mu = expected_returns.mean_historical_return(prbr) ###Matrix de covariancia sigma = risk_models.sample_cov(prbr) ###Fronteira eficiente Max sharpe ef = EfficientFrontier(mu, sigma) weights = ef.max_sharpe() ef.efficient_risk(2.0) ef.efficient_return(1.5) cleaned_weights = ef.clean_weights() print(weights, cleaned_weights) ef.portfolio_performance(verbose=True, risk_free_rate=0.0225) ###Fronteira eficiente Min Vol ef = EfficientFrontier(mu, sigma) raw_weights = ef.min_volatility() cleaned_weights = ef.clean_weights() print(cleaned_weights) ef.portfolio_performance(verbose=True, risk_free_rate=0.02)