⚡️ Speed up function moving_average by 7%
          #483
        
          
      
  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.
  
    
  
    
📄 7% (0.07x) speedup for
moving_averageings_quant/timeseries/technicals.py⏱️ Runtime :
7.22 milliseconds→6.77 milliseconds(best of60runs)📝 Explanation and details
The optimized code achieves a 6% speedup through two key improvements:
1. Reduced
_to_offset()calls innormalize_window()When processing string windows, the original code called
_to_offset(window)twice - once for the window size and once for the ramp value. The optimized version calls it once and reuses the result:This eliminates redundant string parsing and date offset creation, which line profiler shows takes 35-40% of
normalize_window's time.2. Extended vectorized rolling to DataFrames
The original code used pandas' efficient
.rolling().mean()only for Series, falling back to slow list comprehensions for DataFrames. The optimized version uses pandas' vectorized operations for both data types:Performance benefits by test case:
_to_offset()callsThe optimizations maintain identical functionality while leveraging pandas' highly optimized C implementations instead of pure Python loops.
✅ Correctness verification report:
⚙️ Existing Unit Tests and Runtime
timeseries/test_technicals.py::test_moving_average🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-moving_average-mhb5baxkand push.