PyPortfolioOpt icon indicating copy to clipboard operation
PyPortfolioOpt copied to clipboard

Fix dtype warning in HRPOpt: cast weights to float before multiplication

Open Pranav-20186017 opened this issue 9 months ago • 1 comments

Description

This addresses a Future Warning in pypfopt/hierarchical_portfolio.py caused by multiplying integer-type weights with float values. Due to stricter type enforcement, this would cause errors in future pandas versions.

Files Changed

  • pypfopt/hierarchical_portfolio.py

Fix

Explicitly cast weights array to float64 before arithmetic operations:

# Before
w[first_cluster] *= alpha  # weight 1

# After
w = w.astype('float64')  # ensure the weights array is float64
w[first_cluster] *= alpha  # weight 1

Testing Performed

  • [x] Ran full test suite with pytest (no failures)
  • [x] Manually verified warning elimination
  • [x] Confirmed HRP optimization consistency

Checklist

  • [x] Code follows project style guidelines
  • [x] Documentation updated (if applicable)
  • [x] Unit tests pass
  • [x] No unintended side effects

This patch ensures floating-point arithmetic and prevents future dtype conflicts in pandas.

Pranav-20186017 avatar Mar 07 '25 20:03 Pranav-20186017

Good catch but the problem should be addressed right at the definition of w, e.g. use

w = pd.Series(1.0, index=ordered_tickers, dtype='float64')

tschm avatar Nov 16 '25 13:11 tschm