You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
[BUG] DiscreteAllocation crashes with ZeroDivisionError or IndexError on short-only portfolios and zero long weights #781
When constructing a discrete allocation for a dedicated short portfolio (e.g. hedging overlay, inverse leg, or market-neutral short basket) or a portfolio where long assets have 0.0 weight, both greedy_portfolio() and lp_portfolio() crash:
Case 1: ZeroDivisionError with 0.0 long weight
importpandasaspdfrompypfoptimportDiscreteAllocationprices=pd.Series({'AAPL': 150.0, 'MSFT': 250.0})
da=DiscreteAllocation({'AAPL': 0.0, 'MSFT': -1.0}, prices, total_portfolio_value=10000)
# Both crash with ZeroDivisionError:da.greedy_portfolio() # ZeroDivisionError: float division by zero at line 187da.lp_portfolio() # ZeroDivisionError: float division by zero at line 327
Case 2: IndexError on short-only portfolio
importpandasaspdfrompypfoptimportDiscreteAllocationprices=pd.Series({'AAPL': 150.0, 'MSFT': 250.0})
da=DiscreteAllocation({'AAPL': -0.6, 'MSFT': -0.4}, prices, total_portfolio_value=10000)
da.greedy_portfolio() # IndexError: list index out of range at line 180
Root Cause
In pypfopt/discrete_allocation.py, both greedy_portfolio (lines 180-218) and lp_portfolio (lines 320-357) split weights into longs and shorts:
If the portfolio contains only short positions and zero-weight long assets (w == 0.0), long_total_weight is 0.0. Dividing w / long_total_weight raises ZeroDivisionError: float division by zero.
If the portfolio contains only short positions (no positive longs), longs is empty {}. Passing longs to da1 = DiscreteAllocation(longs, ...) and calling da1.greedy_portfolio() fails with IndexError: list index out of range when evaluating self.weights[-1][1] < 0 on an empty weights list.
Expected Behavior
A short-only portfolio or a portfolio without positive long positions should cleanly allocate the short positions without attempting to divide by zero on the empty long sub-portfolio.
Activity