Skip to content

[BUG] DiscreteAllocation crashes with ZeroDivisionError or IndexError on short-only portfolios and zero long weights #781

Open

Description

@Aadrit555

Environment

  • OS: Any
  • Python: 3.10+
  • PyPortfolioOpt: 1.6.0 (and main branch)
  • pandas: 2.x+

Problem & Minimal Reproducing Example

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

import pandas as pd
from pypfopt import DiscreteAllocation

prices = 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 187
da.lp_portfolio()      # ZeroDivisionError: float division by zero at line 327

Case 2: IndexError on short-only portfolio

import pandas as pd
from pypfopt import DiscreteAllocation

prices = 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:

longs = {t: w for t, w in self.weights if w >= 0}
shorts = {t: -w for t, w in self.weights if w < 0}

long_total_weight = sum(longs.values())
short_total_weight = sum(shorts.values())
longs = {t: w / long_total_weight for t, w in longs.items()}
  1. 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.
  2. 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions