⚡️ Speed up function relative_strength_index by 1,601%
#484
+238
−144
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.
📄 1,601% (16.01x) speedup for
relative_strength_indexings_quant/timeseries/technicals.py⏱️ Runtime :
530 milliseconds→31.1 milliseconds(best of42runs)📝 Explanation and details
The optimizations achieve a 1601% speedup by targeting the most expensive computational bottlenecks in the financial technical analysis functions:
Key Performance Optimizations:
Eliminated Pandas overhead in loops - The original
smoothed_moving_averageused expensiveilocassignments in tight loops (64.6% of runtime). The optimized version uses numpy arrays for computations and only creates the final pandas Series once, reducing pandas indexing overhead dramatically.Vectorized array operations - In
relative_strength_index, replaced element-wise pandas operations with numpy'swhere()for gains/losses calculation and vectorized the RSI computation using boolean masks, eliminating the expensive per-element loop that consumed 29.4% of original runtime.Reduced redundant computations - Cached date offset calculations in
smoothed_moving_averagefor non-integer windows, avoiding repeated filtering operations. Also eliminated redundantlen(x)calls and_to_offset()conversions innormalize_window.Memory-efficient data structures - Pre-allocated numpy arrays instead of repeatedly modifying pandas Series, reducing memory allocation overhead and improving cache locality.
Test Case Performance:
The optimizations are particularly effective for high-frequency trading scenarios and batch processing of multiple time series, where these functions are called repeatedly on large datasets. The numpy-based approach scales linearly rather than quadratically with data size.
✅ Correctness verification report:
⚙️ Existing Unit Tests and Runtime
timeseries/test_technicals.py::test_relative_strength_index🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-relative_strength_index-mhb5smfwand push.