PyPortfolioOpt
PyPortfolioOpt copied to clipboard
Fix dtype warning in HRPOpt: cast weights to float before multiplication
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.
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')