Head & Shoulder Chart Pattern

Head & Shoulder Chart Pattern

The Head and Shoulders chart pattern is a technical analysis formation used to predict reversals in market trends. It consists of three peaks:

  1. Left Shoulder: A peak followed by a decline.
  2. Head: A higher peak followed by a decline.
  3. Right Shoulder: A lower peak after the head, followed by a decline.

A neckline is drawn connecting the lows of the two troughs between these peaks. A breakout below the neckline signals a bearish reversal (downtrend).

Python Code:

def detect_head_shoulder(df, window=3):
    # Define the rolling window
    roll_window = window
    # Create a rolling window for High and Low
    df['high_roll_max'] = df['high'].rolling(window=roll_window).max()
    df['low_roll_min'] = df['low'].rolling(window=roll_window).min()
    # Create a boolean mask for Head and Shoulder pattern
    mask_head_shoulder = ((df['high_roll_max'] > df['high'].shift(1)) & (df['high_roll_max'] > df['high'].shift(-1)) & (
                df['high'] < df['high'].shift(1)) & (df['high'] < df['high'].shift(-1)))
    # Create a boolean mask for Inverse Head and Shoulder pattern
    mask_inv_head_shoulder = ((df['low_roll_min'] < df['low'].shift(1)) & (df['low_roll_min'] < df['low'].shift(-1)) & (
                df['low'] > df['low'].shift(1)) & (df['low'] > df['low'].shift(-1)))
    # Create a new column for Head and Shoulder and its inverse pattern and populate it using the boolean masks
    df['head_shoulder_pattern'] = np.nan
    df.loc[mask_head_shoulder, 'head_shoulder_pattern'] = 'Head and Shoulder'
    df.loc[mask_inv_head_shoulder, 'head_shoulder_pattern'] = 'Inverse Head and Shoulder'
    return df

Code credit: https://github.com/white07S/TradingPatternScanner