This code is not optimized for speed, but shows in general how you could solve this problem. This answer only answers your question of finding if the three moving averages have crossed. It does not give you a sell or buy signal, but you could easily implemented it by checking in which direction the signs change in the diff arrays.
Note: The code currently can give duplicates of "The three MA's have crossed", because of looking within a range of 4 candlesticks.
import numpy as np
MA1 = np.asarray([0, 1, 4, 3, 4, 5, 6, 7, 8, 9, 10])
MA2 = np.asarray([0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
MA3 = np.asarray([0, 0, 6, 7, 8, 9, 10, 10, 11, 12, 13])
haveCrossed = False
for i in range(len(MA1)-3):
# These are the differences between the moving averages, if one MA
# crosses another the sign of the difference changes from positive to
# negative or vice versa.
diff1 = MA1[i:i+4] - MA2[i:i+4]
diff2 = MA1[i:i+4] - MA3[i:i+4]
diff3 = MA2[i:i+4] - MA3[i:i+4]
# Check if all signs are equal. If the signs are equal, the moving averages
# did not intersect.
# Check if MA1 and MA2 crossed.
if np.all(diff1 > 0) if diff1[0] > 0 else np.all(diff1 < 0):
cross1Flag = False
else:
cross1Flag = True
# Check if MA1 and MA3 crossed.
if np.all(diff2 > 0) if diff2[0] > 0 else np.all(diff2 < 0):
cross2Flag = False
else:
cross2Flag = True
# Check if MA2 and MA3 crossed.
if np.all(diff3 > 0) if diff3[0] > 0 else np.all(diff3 < 0):
cross3Flag = False
else:
cross3Flag = True
if cross1Flag and cross2Flag and cross3Flag:
haveCrossed = True
print(f"The three Moving Averages crossed at time: [{i}, {i+3}]")
if not haveCrossed:
print("The three Moving Averages have not crossed.")
Output:
The three Moving Averages crossed at time: [0, 3]
The three Moving Averages crossed at time: [1, 4]