diff --git a/pypfopt/cla.py b/pypfopt/cla.py index c2079047..320d389a 100644 --- a/pypfopt/cla.py +++ b/pypfopt/cla.py @@ -56,7 +56,7 @@ def __init__(self, expected_returns, cov_matrix, weight_bounds=(0, 1)): :type cov_matrix: pd.DataFrame or np.array :param weight_bounds: minimum and maximum weight of an asset, defaults to (0, 1). Must be changed to (-1, 1) for portfolios with shorting. - :type weight_bounds: tuple (float, float) or (list/ndarray, list/ndarray) + :type weight_bounds: tuple (float, float) or (list/ndarray, list/ndarray) or list(tuple(float, float)) :raises TypeError: if ``expected_returns`` is not a series, list or array :raises TypeError: if ``cov_matrix`` is not a dataframe or array """ diff --git a/pypfopt/discrete_allocation.py b/pypfopt/discrete_allocation.py index ce1fbbba..834133f0 100644 --- a/pypfopt/discrete_allocation.py +++ b/pypfopt/discrete_allocation.py @@ -162,9 +162,7 @@ def greedy_portfolio(self, reinvest=False, verbose=False): if verbose: print("\nAllocating long sub-portfolio...") da1 = DiscreteAllocation( - longs, - self.latest_prices[longs.keys()], - total_portfolio_value=long_val, + longs, self.latest_prices[longs.keys()], total_portfolio_value=long_val ) long_alloc, long_leftover = da1.greedy_portfolio() @@ -193,14 +191,13 @@ def greedy_portfolio(self, reinvest=False, verbose=False): # First round for ticker, weight in self.weights: price = self.latest_prices[ticker] - # Attempt to buy the lower integer number of shares + # Attempt to buy the lower integer number of shares, which could be zero. n_shares = int(weight * self.total_portfolio_value / price) cost = n_shares * price - if cost > available_funds: - # Buy as many as possible - n_shares = available_funds // price - if n_shares == 0: - print("Insufficient funds") + # As weights are all > 0 (long only) we always round down n_shares + # so the cost is always <= simple weighted share of portfolio value, + # so we can not run out of funds just here. + assert cost <= available_funds, "Unexpectedly insufficient funds." available_funds -= cost shares_bought.append(n_shares) buy_prices.append(price) @@ -286,9 +283,7 @@ def lp_portfolio(self, reinvest=False, verbose=False, solver="GLPK_MI"): if verbose: print("\nAllocating long sub-portfolio:") da1 = DiscreteAllocation( - longs, - self.latest_prices[longs.keys()], - total_portfolio_value=long_val, + longs, self.latest_prices[longs.keys()], total_portfolio_value=long_val ) long_alloc, long_leftover = da1.lp_portfolio() diff --git a/pypfopt/plotting.py b/pypfopt/plotting.py index a06d1682..e4dcce6a 100644 --- a/pypfopt/plotting.py +++ b/pypfopt/plotting.py @@ -13,6 +13,7 @@ from . import risk_models, exceptions from . import EfficientFrontier, CLA import scipy.cluster.hierarchy as sch +import warnings try: import matplotlib.pyplot as plt @@ -100,6 +101,10 @@ def plot_dendrogram(hrp, ax=None, show_tickers=True, **kwargs): ax = ax or plt.gca() if hrp.clusters is None: + warnings.warn( + "hrp param has not been optimized. Attempting optimization.", + RuntimeWarning, + ) hrp.optimize() if show_tickers: diff --git a/pypfopt/risk_models.py b/pypfopt/risk_models.py index 443025d8..45a30839 100644 --- a/pypfopt/risk_models.py +++ b/pypfopt/risk_models.py @@ -303,9 +303,9 @@ def min_cov_determinant( assets = prices.columns if returns_data: - X = prices.dropna(how="all") + X = prices else: - X = prices.pct_change().dropna(how="all") + X = returns_from_prices(prices) X = np.nan_to_num(X.values) raw_cov_array = sklearn.covariance.fast_mcd(X, random_state=random_state)[1] cov = pd.DataFrame(raw_cov_array, index=assets, columns=assets) * frequency @@ -342,7 +342,7 @@ def corr_to_cov(corr_matrix, stdevs): :rtype: pd.DataFrame """ if not isinstance(corr_matrix, pd.DataFrame): - warnings.warn("cov_matrix is not a dataframe", RuntimeWarning) + warnings.warn("corr_matrix is not a dataframe", RuntimeWarning) corr_matrix = pd.DataFrame(corr_matrix) return corr_matrix * np.outer(stdevs, stdevs) diff --git a/tests/test_base_optimizer.py b/tests/test_base_optimizer.py index a1ec9ce0..e08abbaf 100644 --- a/tests/test_base_optimizer.py +++ b/tests/test_base_optimizer.py @@ -6,10 +6,20 @@ import cvxpy as cp from pypfopt import EfficientFrontier from pypfopt import exceptions -from pypfopt.base_optimizer import portfolio_performance +from pypfopt.base_optimizer import portfolio_performance, BaseOptimizer from tests.utilities_for_tests import get_data, setup_efficient_frontier +def test_base_optimizer(): + """ Cover code not covered elsewhere.""" + # Test tickers not provided + bo = BaseOptimizer(2) + assert bo.tickers == [0, 1] + w = {0: 0.4, 1: 0.6} + bo.set_weights(w) + assert dict(bo.clean_weights()) == w + + def test_custom_bounds(): ef = EfficientFrontier( *setup_efficient_frontier(data_only=True), weight_bounds=(0.02, 0.13) @@ -233,7 +243,12 @@ def test_portfolio_performance(): portfolio_performance(ef.weights, ef.expected_returns, ef.cov_matrix, True) == expected ) - + # including when used without expected returns too. + assert portfolio_performance(ef.weights, None, ef.cov_matrix, True) == ( + None, + expected[1], + None, + ) # Internal ticker creations when weights param is a dict and ... w_dict = dict(zip(ef.tickers, ef.weights)) # ... expected_returns is a Series diff --git a/tests/test_black_litterman.py b/tests/test_black_litterman.py index 4001565e..b4026b34 100644 --- a/tests/test_black_litterman.py +++ b/tests/test_black_litterman.py @@ -29,6 +29,10 @@ def test_input_errors(): # Because default_omega uses matrix mult on P BlackLittermanModel(S, Q=views, P=P) + # P not an DataFrame or ndarray + with pytest.raises(TypeError): + BlackLittermanModel(S, Q=views[:-1], P=1.0) + with pytest.raises(AssertionError): BlackLittermanModel(S, Q=views, P=P, omega=np.eye(len(views))) @@ -36,6 +40,22 @@ def test_input_errors(): with pytest.raises(AssertionError): BlackLittermanModel(S, Q=views, pi=df.pct_change().mean()[:-1]) + # If pi=="market" then market_caps must be supplied + with pytest.raises(ValueError): + BlackLittermanModel(S, Q=views, pi="market") + + # pi's valid numerical types are Series, DataFrame and ndarray + with pytest.raises(TypeError): + BlackLittermanModel(S, Q=views, pi=[0.1] * len(S)) + + # risk_aversion cannot be negative + with pytest.raises(ValueError): + BlackLittermanModel(S, Q=views, risk_aversion=-0.01) + + # omega must be ndarray, DataFrame and string + with pytest.raises(TypeError): + BlackLittermanModel(S, Q=views, omega=1.0) + def test_parse_views(): df = get_data() @@ -73,7 +93,8 @@ def test_dataframe_input(): # views on the first 10 assets view_df = pd.DataFrame(pd.Series(0.1, index=S.columns)[:10]) - picking = np.eye(len(S))[:10, :] + # P's index and columns labels are ignored when a DataFrame is used: + picking = pd.DataFrame(np.eye(len(S))[:10, :]) assert BlackLittermanModel(S, Q=view_df, P=picking) prior_df = df.pct_change().mean() @@ -82,6 +103,19 @@ def test_dataframe_input(): assert BlackLittermanModel(S, pi=prior_df, Q=view_df, P=picking, omega=omega_df) +def test_cov_ndarray(): + df = get_data() + prior_df = df.pct_change().mean() + S = risk_models.sample_cov(df) + views = pd.Series(0.1, index=S.columns) + bl = BlackLittermanModel(S, pi=prior_df, Q=views) + bl_nd = BlackLittermanModel(S.to_numpy(), pi=prior_df.to_numpy(), Q=views) + # Compare without missing ticker index values. + np.testing.assert_equal(bl_nd.bl_returns().to_numpy(), bl.bl_returns().to_numpy()) + np.testing.assert_equal(bl_nd.bl_cov().to_numpy(), bl.bl_cov().to_numpy()) + assert list(bl_nd.bl_weights().values()) == list(bl.bl_weights().values()) + + def test_default_omega(): df = get_data() S = risk_models.sample_cov(df) @@ -215,6 +249,11 @@ def test_market_risk_aversion(): delta = black_litterman.market_implied_risk_aversion(prices) assert np.round(delta.iloc[0], 5) == 2.68549 + # Check it raises for other types. + list_invalid = [100.0, 110.0, 120.0, 130.0] + with pytest.raises(TypeError): + delta = black_litterman.market_implied_risk_aversion(list_invalid) + def test_bl_weights(): df = get_data() diff --git a/tests/test_cla.py b/tests/test_cla.py index e0335370..978f3628 100644 --- a/tests/test_cla.py +++ b/tests/test_cla.py @@ -62,6 +62,12 @@ def test_cla_custom_bounds(): np.testing.assert_almost_equal(cla.weights.sum(), 1) assert (0.01 <= cla.weights[::2]).all() and (cla.weights[::2] <= 0.13).all() assert (0.02 <= cla.weights[1::2]).all() and (cla.weights[1::2] <= 0.11).all() + # Test polymorphism of the weight_bounds param. + bounds2 = ([bounds[0][0], bounds[1][0]] * 10, [bounds[0][1], bounds[1][1]] * 10) + cla2 = CLA(*setup_cla(data_only=True), weight_bounds=bounds2) + cla2.cov_matrix = risk_models.exp_cov(df).values + w2 = cla2.min_volatility() + assert dict(w2) == dict(w) def test_cla_min_volatility(): diff --git a/tests/test_custom_objectives.py b/tests/test_custom_objectives.py index 45955635..91e86190 100644 --- a/tests/test_custom_objectives.py +++ b/tests/test_custom_objectives.py @@ -17,6 +17,22 @@ def new_objective(w): np.testing.assert_allclose(ef.weights, np.array([1 / 20] * 20)) +def test_custom_convex_additional(): + ef = setup_efficient_frontier() + ef.add_objective(objective_functions.L2_reg, gamma=1) + w_co = ef.convex_objective( + objective_functions.portfolio_variance, cov_matrix=ef.cov_matrix + ) + + # Same as test_min_volatility_L2_reg: + ef = setup_efficient_frontier() + ef.add_objective(objective_functions.L2_reg, gamma=1) + w_mv = ef.min_volatility() + # Weights from custom convex objective match those from min_volatility where + # an additional objective is applied to both. + assert dict(w_co) == dict(w_mv) + + def test_custom_convex_abs_exposure(): ef = EfficientFrontier( *setup_efficient_frontier(data_only=True), weight_bounds=(None, None) diff --git a/tests/test_discrete_allocation.py b/tests/test_discrete_allocation.py index dafe77b0..a86e20ec 100644 --- a/tests/test_discrete_allocation.py +++ b/tests/test_discrete_allocation.py @@ -40,14 +40,14 @@ def test_greedy_portfolio_allocation(): da = DiscreteAllocation(w, latest_prices, short_ratio=0.3) allocation, leftover = da.greedy_portfolio() - assert { - "MA": 14, + assert allocation == { + "MA": 20, "FB": 12, - "PFE": 51, - "BABA": 5, - "AAPL": 5, - "BBY": 9, - "SBUX": 6, + "PFE": 54, + "BABA": 4, + "AAPL": 4, + "BBY": 2, + "SBUX": 1, "GOOG": 1, } @@ -56,6 +56,11 @@ def test_greedy_portfolio_allocation(): total += num * latest_prices[ticker] np.testing.assert_almost_equal(total + leftover, 10000, decimal=4) + # Cover the verbose parameter, + allocation_verbose, leftover_verbose = da.greedy_portfolio(verbose=True) + assert allocation_verbose == allocation + assert leftover_verbose == leftover + def test_greedy_allocation_rmse_error(): df = get_data() @@ -114,6 +119,11 @@ def test_greedy_portfolio_allocation_short(): long_total + short_total + leftover, 13000, decimal=4 ) + # Cover the verbose parameter, + allocation_verbose, leftover_verbose = da.greedy_portfolio(verbose=True) + assert allocation_verbose == allocation + assert leftover_verbose == leftover + def test_greedy_allocation_rmse_error_short(): df = get_data() @@ -257,6 +267,11 @@ def test_lp_portfolio_allocation(): total += num * latest_prices[ticker] np.testing.assert_almost_equal(total + leftover, 10000, decimal=4) + # Cover the verbose parameter, + allocation_verbose, leftover_verbose = da.lp_portfolio(verbose=True) + assert allocation_verbose == allocation + assert leftover_verbose == leftover + def test_lp_allocation_rmse_error(): df = get_data() @@ -315,6 +330,11 @@ def test_lp_portfolio_allocation_short(): long_total + short_total + leftover, 13000, decimal=5 ) + # Cover the verbose parameter, + allocation_verbose, leftover_verbose = da.lp_portfolio(verbose=True) + assert allocation_verbose == allocation + assert leftover_verbose == leftover + def test_lp_portfolio_allocation_short_reinvest(): df = get_data() diff --git a/tests/test_expected_returns.py b/tests/test_expected_returns.py index d398a5ec..f92b520c 100644 --- a/tests/test_expected_returns.py +++ b/tests/test_expected_returns.py @@ -272,3 +272,9 @@ def test_return_model_not_implemented(): df = get_data() with pytest.raises(NotImplementedError): expected_returns.return_model(df, method="fancy_new!") + + +def test_james_stein_shrinkage(): + df = get_data() + with pytest.raises(NotImplementedError): + expected_returns.james_stein_shrinkage(df) diff --git a/tests/test_hrp.py b/tests/test_hrp.py index 96987a8e..7f39c663 100644 --- a/tests/test_hrp.py +++ b/tests/test_hrp.py @@ -6,6 +6,21 @@ from tests.utilities_for_tests import get_data, resource +def test_hrp_errors(): + with pytest.raises(ValueError): + hrp = HRPOpt() + + df = get_data() + returns = df.pct_change().dropna(how="all") + returns_np = returns.to_numpy() + with pytest.raises(TypeError): + hrp = HRPOpt(returns_np) + + hrp = HRPOpt(returns) + with pytest.raises(ValueError): + hrp.optimize(linkage_method="blah") + + def test_hrp_portfolio(): df = get_data() returns = df.pct_change().dropna(how="all") diff --git a/tests/test_plotting.py b/tests/test_plotting.py index 7e6dc450..848cc0a6 100644 --- a/tests/test_plotting.py +++ b/tests/test_plotting.py @@ -1,6 +1,8 @@ import numpy as np import matplotlib import matplotlib.pyplot as plt +import os +import pytest from tests.utilities_for_tests import get_data, setup_efficient_frontier from pypfopt import plotting, risk_models, expected_returns from pypfopt import HRPOpt, CLA, EfficientFrontier @@ -9,14 +11,29 @@ def test_correlation_plot(): plt.figure() df = get_data() - S = risk_models.CovarianceShrinkage(df).ledoit_wolf() ax = plotting.plot_covariance(S, showfig=False) assert len(ax.findobj()) == 256 plt.clf() + ax = plotting.plot_covariance(S, plot_correlation=True, showfig=False) + assert len(ax.findobj()) == 256 + plt.clf() ax = plotting.plot_covariance(S, show_tickers=False, showfig=False) assert len(ax.findobj()) == 136 plt.clf() + ax = plotting.plot_covariance( + S, plot_correlation=True, show_tickers=False, showfig=False + ) + assert len(ax.findobj()) == 136 + plt.clf() + + plot_filename = "tests/plot.png" + ax = plotting.plot_covariance(S, filename=plot_filename, showfig=False) + assert len(ax.findobj()) == 256 + assert os.path.exists(plot_filename) + assert os.path.getsize(plot_filename) > 0 + os.remove(plot_filename) + plt.clf() plt.close() @@ -38,6 +55,21 @@ def test_dendrogram_plot(): plt.clf() plt.close() + # Test that passing an unoptimized HRPOpt works, but issues a warning as + # this should already have been optimized according to the API. + hrp = HRPOpt(returns) + with pytest.warns(RuntimeWarning) as w: + ax = plotting.plot_dendrogram(hrp, show_tickers=False, showfig=False) + assert len(w) == 1 + assert ( + str(w[0].message) + == "hrp param has not been optimized. Attempting optimization." + ) + assert len(ax.findobj()) == 65 + assert type(ax.findobj()[0]) == matplotlib.collections.LineCollection + plt.clf() + plt.close() + def test_cla_plot(): plt.figure() @@ -99,6 +131,24 @@ def test_ef_plot_utility(): plt.close() +def test_ef_plot_errors(): + plt.figure() + ef = setup_efficient_frontier() + delta_range = np.arange(0.001, 100, 1) + # Test invalid ef_param + with pytest.raises(NotImplementedError): + ax = plotting.plot_efficient_frontier( + ef, ef_param="blah", ef_param_range=delta_range, showfig=False + ) + # Test invalid optimizer + with pytest.raises(NotImplementedError): + ax = plotting.plot_efficient_frontier( + None, ef_param_range=delta_range, showfig=False + ) + plt.clf() + plt.close() + + def test_ef_plot_risk(): plt.figure() ef = setup_efficient_frontier() @@ -115,10 +165,13 @@ def test_ef_plot_risk(): plt.close() -def ef_plot_return(): +def test_ef_plot_return(): plt.figure() ef = setup_efficient_frontier() - return_range = np.linspace(0, ef.expected_returns.max(), 50) + # FIXME: Internally _max_return() is used, which uses a solver so can have numerical differences to the inputs. + # hence the epsilon here + max_ret = ef.expected_returns.max() - 0.0001 + return_range = np.linspace(0, max_ret, 50) ax = plotting.plot_efficient_frontier( ef, ef_param="return", ef_param_range=return_range, showfig=False ) diff --git a/tests/test_risk_models.py b/tests/test_risk_models.py index 157443d6..792104ff 100644 --- a/tests/test_risk_models.py +++ b/tests/test_risk_models.py @@ -69,6 +69,17 @@ def test_sample_cov_npd(): str(w[0].message) == "The covariance matrix is non positive semidefinite. Amending eigenvalues." ) + # Test works on DataFrame too, same results, index and columns rebuilt. + tickers = ["A", "B"] + S_df = pd.DataFrame(data=S, index=tickers, columns=tickers) + S2_df = risk_models.fix_nonpositive_semidefinite(S_df, fix_method=method) + assert isinstance(S2_df, pd.DataFrame) + np.testing.assert_equal(S2_df.to_numpy(), S2) + assert S2_df.index.equals(S_df.index) + assert S2_df.columns.equals(S_df.columns) + + with pytest.raises(NotImplementedError): + risk_models.fix_nonpositive_semidefinite(S, fix_method="blah") def test_fix_npd_different_method(): @@ -96,6 +107,10 @@ def test_semicovariance(): assert risk_models._is_positive_semidefinite(S) S2 = risk_models.semicovariance(df, frequency=2) pd.testing.assert_frame_equal(S / 126, S2) + # Cover that it works on np.ndarray, with a warning + with pytest.warns(RuntimeWarning): + S2_np = risk_models.semicovariance(df.to_numpy(), frequency=2) + np.testing.assert_equal(S2_np, S2.to_numpy()) def test_semicovariance_benchmark(): @@ -120,6 +135,13 @@ def test_exp_cov_matrix(): assert risk_models._is_positive_semidefinite(S) S2 = risk_models.exp_cov(df, frequency=2) pd.testing.assert_frame_equal(S / 126, S2) + # Cover that it works on np.ndarray, with a warning + with pytest.warns(RuntimeWarning): + S2_np = risk_models.exp_cov(df.to_numpy(), frequency=2) + np.testing.assert_equal(S2_np, S2.to_numpy()) + # Too short a span causes a warning. + with pytest.warns(UserWarning): + risk_models.exp_cov(df, frequency=2, span=9) def test_exp_cov_limits(): @@ -141,6 +163,11 @@ def test_min_cov_det(): assert S.index.equals(S.columns) assert S.notnull().all().all() # assert risk_models._is_positive_semidefinite(S) + # Cover that it works on np.ndarray, with a warning + with pytest.warns(RuntimeWarning): + S2 = risk_models.min_cov_determinant(df.to_numpy(), random_state=8) + assert isinstance(S2, pd.DataFrame) + np.testing.assert_equal(S.to_numpy(), S2.to_numpy()) def test_cov_to_corr(): @@ -153,6 +180,7 @@ def test_cov_to_corr(): test_corr_numpy = risk_models.cov_to_corr(rets.cov().values) assert len(w) == 1 assert str(w[0].message) == "cov_matrix is not a dataframe" + assert isinstance(test_corr_numpy, pd.DataFrame) np.testing.assert_array_almost_equal(test_corr_numpy, rets.corr().values) @@ -163,6 +191,13 @@ def test_corr_to_cov(): new_cov = risk_models.corr_to_cov(test_corr, rets.std()) pd.testing.assert_frame_equal(new_cov, rets.cov()) + with pytest.warns(RuntimeWarning) as w: + cov_numpy = risk_models.corr_to_cov(test_corr.to_numpy(), rets.std()) + assert len(w) == 1 + assert str(w[0].message) == "corr_matrix is not a dataframe" + assert isinstance(cov_numpy, pd.DataFrame) + np.testing.assert_equal(cov_numpy.to_numpy(), new_cov.to_numpy()) + def test_covariance_shrinkage_init(): df = get_data() @@ -181,6 +216,13 @@ def test_shrunk_covariance(): assert list(shrunk_cov.columns) == list(df.columns) assert not shrunk_cov.isnull().any().any() assert risk_models._is_positive_semidefinite(shrunk_cov) + with pytest.warns(RuntimeWarning) as w: + cs_numpy = risk_models.CovarianceShrinkage(df.to_numpy()) + assert len(w) == 1 + assert str(w[0].message) == "data is not in a dataframe" + shrunk_cov_numpy = cs_numpy.shrunk_covariance(0.2) + assert isinstance(shrunk_cov_numpy, pd.DataFrame) + np.testing.assert_equal(shrunk_cov_numpy.to_numpy(), shrunk_cov.to_numpy()) def test_shrunk_covariance_extreme_delta(): @@ -269,6 +311,7 @@ def test_risk_matrix_and_returns_data(): "sample_cov", "semicovariance", "exp_cov", + # FIXME: this fails "min_cov_determinant", "ledoit_wolf", "ledoit_wolf_constant_variance", "ledoit_wolf_single_factor",