To vectorize the calculations inside the check_atr_touch function and significantly improve performance, we can utilize NumPy arrays and the Numba library for just-in-time compilation. Since the comparison levels (+1ATR and -3ATR) change for each row, completely eliminating the loop over rows is challenging. However, we can optimize the computations within the loop and compile the function to machine code using Numba for speed.
Here is the vectorized version of your function:
import numpy as np
import pandas as pd
from numba import njit
def check_atr_touch_vectorized(df):
# Extract the required columns as NumPy arrays for better performance
close = df['Close'].values
up_level = df['+1ATR'].values
down_level = df['-3ATR'].values
N = len(df)
# Call the Numba-compiled function
results = check_atr_touch_numba(close, up_level, down_level, N)
# Assign the results back to the DataFrame
df['Result'] = results
@njit
def check_atr_touch_numba(close, up_level, down_level, N):
# Initialize the results array with NaN
results = np.full(N, np.nan)
for i in range(N):
# Future Close prices from i+1 to the end
future_close = close[i+1:]
# Check for crossings with +1ATR and -3ATR levels
up_touch = future_close >= up_level[i]
down_touch = future_close <= down_level[i]
# Find the indices where the conditions are True
up_touch_indices = np.where(up_touch)[0]
down_touch_indices = np.where(down_touch)[0]
# Initialize indices to a large number if no touch is found
up_touch_idx = up_touch_indices[0] if up_touch_indices.size > 0 else N
down_touch_idx = down_touch_indices[0] if down_touch_indices.size > 0 else N
# Compare the indices to determine which level was touched first
if up_touch_idx < down_touch_idx:
results[i] = 1 # "+1ATR" touched first
elif down_touch_idx < up_touch_idx:
results[i] = -1 # "-3ATR" touched first
elif up_touch_idx < N:
results[i] = 1 # Only "+1ATR" was touched
elif down_touch_idx < N:
results[i] = -1 # Only "-3ATR" was touched
else:
results[i] = np.nan # Neither level was touched
return results
# Example usage
# Assuming 'df' is your DataFrame with 'Close', '+1ATR', and '-3ATR' columns
check_atr_touch_vectorized(df)
Explanation:
- NumPy Arrays: We extract the relevant columns (
Close, +1ATR, -3ATR) as NumPy arrays for efficient computation.
- Numba JIT Compilation: Using the
@njit decorator from Numba, we compile the check_atr_touch_numba function to optimized machine code.
- Vectorized Computation within Loop: Although we iterate over each row (which is necessary because the comparison levels change per row), we use vectorized operations within the loop to process future Close prices.
- Efficient Indexing: We use
np.where to find the indices where the conditions are met and efficiently determine which event occurs first.
Benefits:
- Performance: This approach significantly speeds up the computation compared to the nested loops in your original function.
- Scalability: The use of Numba and NumPy allows the function to handle large DataFrames efficiently.
Note:
- The
check_atr_touch_vectorized function replaces your original check_atr_touch function.
- Ensure that you have Numba installed (
pip install numba) to use the @njit decorator.
- The function assumes that the DataFrame
df contains the columns 'Close', '+1ATR', and '-3ATR'.
This vectorized solution should provide you with the performance improvements you're seeking while maintaining the logic of your original function.