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

37 lines
1.1 KiB
Python

import numpy as np
def movingStd(x, T, period=None):
"""
Python implementation of the MATLAB movingStd function.
Calculates the standard deviation over a rolling window of T days.
Parameters:
x (ndarray): Input array for moving standard deviation calculation
T (int): Window size for standard deviation calculation
period (int, optional): If provided, data is sampled every 'period'
Returns:
ndarray: Moving standard deviation with NaNs at the beginning
"""
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 output array with NaNs
sd = np.full_like(x, np.nan)
if period is None:
# Regular moving standard deviation
for t in range(T, rows + 1):
sd[t-1, :] = np.std(x[t-T:t, :], axis=0, ddof=0) # Using ddof=0 to normalize by N (not N-1)
else:
# Moving standard deviation with period
for t in range(T*period, rows + 1):
sd[t-1, :] = np.std(x[t-T*period:t, :], axis=0, ddof=0)
return sd