Skip to content
Merged
2 changes: 1 addition & 1 deletion pypfopt/cla.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
"""
Expand Down
19 changes: 7 additions & 12 deletions pypfopt/discrete_allocation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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()

Expand Down
5 changes: 5 additions & 0 deletions pypfopt/plotting.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
6 changes: 3 additions & 3 deletions pypfopt/risk_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
19 changes: 17 additions & 2 deletions tests/test_base_optimizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down
41 changes: 40 additions & 1 deletion tests/test_black_litterman.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,33 @@ 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)))

# pi and S don't match dimensions
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()
Expand Down Expand Up @@ -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()
Expand All @@ -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)
Expand Down Expand Up @@ -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()
Expand Down
6 changes: 6 additions & 0 deletions tests/test_cla.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand Down
16 changes: 16 additions & 0 deletions tests/test_custom_objectives.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
34 changes: 27 additions & 7 deletions tests/test_discrete_allocation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}

Expand All @@ -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()
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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()
Expand Down
6 changes: 6 additions & 0 deletions tests/test_expected_returns.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
15 changes: 15 additions & 0 deletions tests/test_hrp.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
Loading