I have this code that works. I was wondering how to implement using np.lib.stride_tricks.as_strided or avoid loops.
import yfinance as yf
import pandas as pd
import numpy as np
# Fetch Apple stock data
apple_data = yf.download('AAPL', start='2024-01-01', end='2024-03-31')
# Extract volume data
apple_volume = apple_data['Volume']
# Resample to ensure every date is included
apple_volume = apple_volume.resample('D').ffill()
# Function to calculate rolling sum with reset using NumPy
def 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_sums
rolling_3_day_volume = rolling_sum_with_reset(apple_volume, 3)

If the
arrhas a multiple ofwindowssize, it can be reshaped to a 2d array, and cumsum applied to each row:That matches your result:
I think
cumsumcan be used with some sort of 'reset' step array, but this reshape approach is so much easier.as_stridedcan be used to create the windows, but since you don't need overlap in the windows, the result is the same as thisreshape:for size 10 window