⚡️ Speed up function build_exposure_df by 11%
#482
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
📄 11% (0.11x) speedup for
build_exposure_dfings_quant/markets/portfolio_manager_utils.py⏱️ Runtime :
93.0 milliseconds→83.5 milliseconds(best of76runs)📝 Explanation and details
The optimized code achieves an 11% speedup through two key vectorization improvements:
1. Vectorized Column Multiplication (Primary Optimization)
The original code used a loop to multiply each sensitivity column by notional values:
The optimized version uses vectorized NumPy operations:
This eliminates the Python loop overhead and leverages NumPy's efficient broadcasting, which is particularly beneficial for larger datasets as shown in the test results.
2. Improved DataFrame Concatenation Pattern
Instead of chaining
.agg("sum").to_frame().rename().T, the optimized code pre-creates the aggregated row with the correct name:Performance Impact by Test Case:
The optimizations particularly excel when processing many factors and assets simultaneously, making this well-suited for portfolio analysis workloads with substantial data volumes.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-build_exposure_df-mhb51lmnand push.