Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 14040

How to rework rolling sum using Numpy.strides?

$
0
0

I have this code that works. I was wondering how to implement usingnp.lib.stride_tricks.as_strided or avoid loops.

import yfinance as yfimport pandas as pdimport numpy as np# Fetch Apple stock dataapple_data = yf.download('AAPL', start='2024-01-01', end='2024-03-31')# Extract volume dataapple_volume = apple_data['Volume']# Resample to ensure every date is includedapple_volume = apple_volume.resample('D').ffill()# Function to calculate rolling sum with reset using NumPydef rolling_sum_with_reset(series, window_size):    rolling_sums = np.zeros(len(series))    current_sum = 0    for i, value in enumerate(series):        if i % window_size == 0:            current_sum = 0        current_sum += value        rolling_sums[i] = current_sum    return rolling_sumsrolling_3_day_volume = rolling_sum_with_reset(apple_volume, 3)

Viewing all articles
Browse latest Browse all 14040

Trending Articles