34 lines
1007 B
Python
34 lines
1007 B
Python
import numpy as np
|
|
|
|
def backshift(day, x):
|
|
"""
|
|
Python implementation of the MATLAB backshift function.
|
|
|
|
Parameters:
|
|
day (int): Number of days to shift back
|
|
x (ndarray): Input array to be shifted
|
|
|
|
Returns:
|
|
ndarray: Shifted array with NaNs at the beginning
|
|
"""
|
|
assert day >= 0
|
|
|
|
if isinstance(x, list):
|
|
x = np.array(x)
|
|
|
|
# Get the shape information
|
|
shape = x.shape
|
|
|
|
if len(shape) == 1:
|
|
# 1D array case
|
|
y = np.concatenate([np.full(day, np.nan), x[:-day]]) if day > 0 else x.copy()
|
|
elif len(shape) == 2:
|
|
# 2D array case (most common for financial data)
|
|
y = np.vstack([np.full((day, shape[1]), np.nan), x[:-day, :]]) if day > 0 else x.copy()
|
|
elif len(shape) == 3:
|
|
# 3D array case
|
|
y = np.concatenate([np.full((day, shape[1], shape[2]), np.nan), x[:-day, :, :]]) if day > 0 else x.copy()
|
|
else:
|
|
raise ValueError("Input array has too many dimensions")
|
|
|
|
return y |