2025-06-05 08:48:33 +02:00

43 lines
1.0 KiB
Python

import numpy as np
def movingAvg(x, T):
"""
Python implementation of the MATLAB movingAvg function.
Creates a moving average series over T days.
Parameters:
x (ndarray): Input array for moving average calculation
T (int): Number of periods to average over
Returns:
ndarray: Moving average with NaNs in the beginning
"""
assert T > 0
if isinstance(x, list):
x = np.array(x)
# Get dimensions
if len(x.shape) == 1:
x = x.reshape(-1, 1)
rows, cols = x.shape
# Initialize the result array
mvavg = np.zeros((rows - T + 1, cols))
# Calculate the sum for each position
for i in range(T):
mvavg += x[i:rows-T+1+i, :]
# Divide by T to get the average
mvavg = mvavg / T
# Add NaNs at the beginning
result = np.vstack([np.full((T-1, cols), np.nan), mvavg])
# If original input was a vector, return a vector
if cols == 1 and len(x.shape) == 1:
result = result.flatten()
return result