Can you modify Calculate SMI function to include Multi-timeframe (MTF) functionality, create an input and set timeframe to 5 minutes.
Assistant
Certainly! Here's the modified calculate_smi function that includes Multi-timeframe (MTF) functionality with an input parameter timeframe. The function resamples the data to the specified timeframe (set to '5T' for 5 minutes) before calculating the SMI:
python
@staticmethod
def calculate_smi(
data: pd.DataFrame,
k_length: int,
d_length: int,
ema_length: int,
timeframe: str = '5T' # Set default timeframe to 5 minutes
) -> Tuple[np.array, np.array]:
# Ensure the DataFrame index is a DatetimeIndex
if not isinstance(data.index, pd.DatetimeIndex):
raise ValueError("DataFrame index must be a DatetimeIndex for resampling.")
# Resample data to the desired timeframe
data_resampled = data.resample(timeframe).agg({
'open': 'first',
'high': 'max',
'low': 'min',
'close': 'last'
}).dropna() # Drop any periods that didn't have data
highest_high = data_resampled['high'].rolling(window=k_length).max()
lowest_low = data_resampled['low'].rolling(window=k_length).min()
rel_range = data_resampled['close'] - (highest_high + lowest_low) / 2
highest_lowest_range = highest_high - lowest_low
# Double EMA calculation
def double_ema(series: pd.Series, length: int) -> pd.Series:
ema_first = series.ewm(span=length, adjust=False).mean()
ema_second = ema_first.ewm(span=length, adjust=False).mean()
return ema_second
numerator = double_ema(rel_range, d_length)
denominator = double_ema(highest_lowest_range, d_length)
smi = 200 * (numerator / denominator)
smi_ema = smi.ewm(span=ema_length, adjust=False).mean()
return smi.values, smi_ema.values
Explanation:
Timeframe Input: Added a new parameter timeframe with a default value of '5T', which represents 5 minutes in Pandas offset aliases.
Resampling: Used data.resample(timeframe) to resample the data to the specified timeframe. The agg function aggregates the resampled data:
'open': First value in the timeframe.
'high': Maximum value in the timeframe.
'low': Minimum value in the timeframe.
'close': Last value in the timeframe.
Index Check: Added a check to ensure that the DataFrame's index is a DatetimeIndex, which is necessary for resampling.
Drop NaNs: Used .dropna() after resampling to remove any periods without data.
Calculation: Proceeded with the SMI calculation using the resampled data.
Return Values: Returned the SMI and its EMA as NumPy arrays.
Usage Example:
python
# Assuming 'df' is your DataFrame with columns ['open', 'high', 'low', 'close'] and a DatetimeIndex
smi_values, smi_ema_values = calculate_smi(
data=df,
k_length=14,
d_length=3,
ema_length=3,
timeframe='5T' # Set to 5-minute timeframe
)
This modification allows the function to calculate the SMI on resampled data at a 5-minute timeframe, providing you with the Multi-timeframe functionality you requested.