2. Chart Patterns

30 minbeginner

2. Chart Patterns

Introduction: The Language of Price Action

Chart patterns are the visual language of technical analysis - they represent the collective psychology of market participants expressed through price movements over time. These patterns emerge from the repetitive behavior of traders and investors as they react to similar market conditions, creating recognizable formations that technical analysts use to predict future price movements.

The study of chart patterns is based on the principle that human psychology is consistent and that similar market conditions will produce similar price reactions. When a stock reaches a certain price level where many investors previously bought, creating a "floor" of support, technical analysts expect that level to hold again because the same psychological forces are at work. Similarly, when a stock approaches a price level where many investors previously sold, creating a "ceiling" of resistance, analysts expect that level to act as a barrier again.

Chart patterns fall into two primary categories: reversal patterns and continuation patterns. Reversal patterns signal that the current trend is likely to change direction, marking potential turning points in the market. Continuation patterns suggest that the current trend is pausing to consolidate before resuming in the same direction. Understanding how to identify, interpret, and trade these patterns is fundamental to technical analysis.

The effectiveness of chart patterns comes from their ability to capture the balance between supply and demand in the market. When demand exceeds supply, prices rise, creating bullish patterns. When supply exceeds demand, prices fall, creating bearish patterns. The specific shape of these patterns - whether they're triangles, head and shoulders, or flags - tells the story of how this supply-demand balance is shifting.

Basic Chart Types

Before we can identify patterns, we must understand the different ways price data can be displayed. Each chart type presents the same underlying price information but emphasizes different aspects of market behavior. The choice of chart type can significantly affect pattern recognition and trading decisions.

Line Charts

Line charts are the simplest form of price visualization, connecting closing prices with a continuous line. This simplicity makes line charts excellent for identifying overall trends and major support and resistance levels without the visual clutter of more detailed chart types.

Line Chart: A chart that displays price data by connecting closing prices with a continuous line. Line charts show only one price point per period (typically the closing price), making them ideal for identifying trends and major price movements.

Line charts excel at showing the "big picture" - the overall direction of price movement over time. By eliminating the visual noise of intraday price fluctuations, line charts help traders focus on the essential trend. This makes them particularly useful for longer-term analysis, where daily or weekly closing prices are more relevant than intraday volatility.

However, line charts sacrifice important information. They don't show the opening price, the high, or the low for each period - information that can be crucial for understanding market sentiment and identifying certain patterns. A stock might close at the same price on two consecutive days, but if one day had a large intraday range while the other was quiet, the line chart would show them identically, missing important information about volatility and market behavior.

Bar Charts

Bar charts provide more information than line charts by displaying the high, low, open, and close prices for each period. Each bar represents one time period (day, week, hour, etc.) and shows the full price range during that period.

Bar Chart: A chart that displays price data using vertical bars, where each bar shows the high, low, open, and close prices for a single time period. The top of the bar represents the high, the bottom represents the low, a tick on the left represents the open, and a tick on the right represents the close.

The visual structure of a bar chart tells a story about market behavior during each period. A long bar indicates high volatility and significant price movement, while a short bar suggests a quiet, range-bound period. The position of the open and close ticks relative to the high and low shows whether buyers or sellers were in control - if the close is near the high, buyers dominated; if the close is near the low, sellers dominated.

Bar charts are particularly useful for identifying patterns that depend on the relationship between the high, low, open, and close. For example, a pattern where the close is consistently near the high of each bar suggests strong buying pressure, while closes consistently near the low suggest selling pressure. This information is essential for understanding market dynamics and identifying reversal and continuation patterns.

Candlestick Charts

Candlestick charts, developed in Japan in the 18th century, provide the same information as bar charts but in a more visually intuitive format. They've become the most popular chart type among technical analysts because they make it easier to identify patterns and understand market sentiment at a glance.

Candlestick Chart: A chart that displays price data using candlestick formations, where each candlestick shows the high, low, open, and close prices for a single time period. The body of the candle (the thick part) shows the range between the open and close, while the wicks (thin lines) show the high and low.

Candlestick charts use color coding to immediately convey market sentiment. In most charting systems, a green (or white) candle indicates that the close was higher than the open (bullish), while a red (or black) candle indicates that the close was lower than the open (bearish). This visual distinction makes it easy to see at a glance whether buyers or sellers controlled each period.

The size and shape of candlesticks provide additional information. A long body suggests strong buying or selling pressure, while a short body (called a doji) suggests indecision and potential reversal. Long wicks indicate that prices moved significantly beyond the open-close range before being rejected, which can signal support or resistance levels. This rich visual information makes candlestick charts particularly powerful for pattern recognition.

Python exercise

#| label: fig-chart-types-comparison
#| fig-cap: "Chart Types Comparison: Enhanced Analysis - Information Density, Pattern Recognition, and Use Cases"
#| fig-width: 18
#| fig-height: 12

# Sandbox metadata (auto-generated from lesson.ts)
# libraries: numpy, matplotlib, pandas

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.patches import Rectangle
import numpy as np
from datetime import datetime, timedelta
from IPython.display import display

# Generate sample price data (30 days) with some volatility
np.random.seed(42)
dates = [datetime(2024, 1, 1) + timedelta(days=i) for i in range(30)]
base_price = 100
prices = [base_price]
for i in range(29):
    if i < 10:
        change = 0.5 + np.random.normal(0, 1.5)
    elif i < 20:
        change = -0.3 + np.random.normal(0, 2)
    else:
        change = 0.8 + np.random.normal(0, 1.5)
    prices.append(max(prices[-1] + change, 85))

# Generate OHLC data from prices
opens = prices[:-1]
closes = prices[1:]
highs = [max(o, c) + abs(np.random.normal(0, 1.2)) for o, c in zip(opens, closes)]
lows = [min(o, c) - abs(np.random.normal(0, 1.2)) for o, c in zip(opens, closes)]

dates_aligned = dates[1:]

# Create 4-panel figure
fig = plt.figure(figsize=(18, 12))
gs = fig.add_gridspec(2, 2, hspace=0.35, wspace=0.3, height_ratios=[1.5, 1])
fig.suptitle('Chart Types Comparison: Enhanced Analysis - Information Density, Pattern Recognition, and Use Cases', 
             fontsize=17, fontweight='bold', y=0.98)

# Panel 1: Line Chart
ax1 = fig.add_subplot(gs[0, 0])
ax1.plot(dates_aligned, closes, color='#2E86AB', linewidth=2.5, marker='o', markersize=5, alpha=0.8)

# Add trendline
z = np.polyfit(range(len(closes)), closes, 1)
p = np.poly1d(z)
ax1.plot(dates_aligned, p(range(len(closes))), '--', color='orange', linewidth=2, alpha=0.7, label='Trendline')

ax1.set_title('Panel 1: Line Chart - Trend Analysis (Closing Prices Only)', fontsize=13, fontweight='bold')
ax1.set_ylabel('Price ($)', fontsize=11, fontweight='bold')
ax1.legend(loc='upper left', fontsize=9)
ax1.grid(True, alpha=0.3, linestyle='--')
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d'))

# Panel 2: Bar Chart
ax2 = fig.add_subplot(gs[0, 1])
for i, (date, high, low, open_price, close_price) in enumerate(zip(dates_aligned, highs, lows, opens, closes)):
    # Vertical line for high-low range
    ax2.plot([date, date], [low, high], color='black', linewidth=1.5, alpha=0.7)
    # Left tick for open
    ax2.plot([date, date], [open_price-0.4, open_price+0.4], color='black', linewidth=3)
    # Right tick for close
    ax2.plot([date, date], [close_price-0.4, close_price+0.4], color='black', linewidth=3)
    # Color based on open vs close
    if close_price > open_price:
        ax2.plot([date, date], [open_price, close_price], color='#2ecc71', linewidth=5, alpha=0.8)
    else:
        ax2.plot([date, date], [close_price, open_price], color='#e74c3c', linewidth=5, alpha=0.8)

ax2.set_title('Panel 2: Bar Chart - Full OHLC Information (High, Low, Open, Close)', 
              fontsize=13, fontweight='bold')
ax2.set_ylabel('Price ($)', fontsize=11, fontweight='bold')
ax2.grid(True, alpha=0.3, linestyle='--')
ax2.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d'))

# Panel 3: Candlestick Chart
ax3 = fig.add_subplot(gs[1, :])
for i, (date, high, low, open_price, close_price) in enumerate(zip(dates_aligned, highs, lows, opens, closes)):
    # Wick (high-low line)
    ax3.plot([date, date], [low, high], color='black', linewidth=1, alpha=0.6)
    # Body
    body_height = abs(close_price - open_price)
    body_bottom = min(open_price, close_price)
    color = '#2ecc71' if close_price > open_price else '#e74c3c'
    rect = Rectangle((mdates.date2num(date) - 0.35, body_bottom), 0.7, body_height, 
                     facecolor=color, edgecolor='black', linewidth=1, alpha=0.9)
    ax3.add_patch(rect)

# Highlight a pattern (doji-like candle)
doji_idx = 15
ax3.annotate('Doji Pattern\n(Open ≈ Close)', 
            xy=(dates_aligned[doji_idx], closes[doji_idx]), xytext=(15, 25),
            textcoords='offset points', fontsize=9, fontweight='bold',
            bbox=dict(boxstyle='round', facecolor='yellow', alpha=0.8),
            arrowprops=dict(arrowstyle='->', color='black', lw=1.5))

ax3.set_title('Panel 3: Candlestick Chart - Pattern Recognition (Visual OHLC with Color Coding)', 
              fontsize=13, fontweight='bold')
ax3.set_xlabel('Date', fontsize=11, fontweight='bold')
ax3.set_ylabel('Price ($)', fontsize=11, fontweight='bold')
ax3.grid(True, alpha=0.3, linestyle='--')
ax3.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d'))

# Panel 4: Comparison Table and Use Cases
ax4 = fig.add_subplot(gs[1, 0])
ax4.axis('off')

# Calculate information metrics
line_info = 1  # Only close
bar_info = 4   # OHLC
candle_info = 4  # OHLC but visually enhanced

info_density = ['Line Chart', 'Bar Chart', 'Candlestick']
info_values = [line_info, bar_info, candle_info]
colors_info = ['#3498db', '#e67e22', '#16a085']

bars = ax4.barh(info_density, info_values, color=colors_info, alpha=0.7, edgecolor='black', linewidth=1.5)
for bar, val in zip(bars, info_values):
    width = bar.get_width()
    ax4.text(width + 0.1, bar.get_y() + bar.get_height()/2,
            f'{val} data points', ha='left', va='center', fontsize=10, fontweight='bold')

ax4.set_title('Panel 4: Information Density Comparison', fontsize=12, fontweight='bold')
ax4.set_xlim(0, 5)
ax4.set_xlabel('Data Points per Period', fontsize=11, fontweight='bold')

# Add comparison text
comparison_text = f"""
Chart Type Comparison:

Information Content:
• Line: 1 data point (Close only)
• Bar: 4 data points (OHLC)
• Candlestick: 4 data points (OHLC, visual)

Use Cases:
• Line: Long-term trends, simplicity
• Bar: Full OHLC, precise analysis
• Candlestick: Pattern recognition, visual clarity

Pattern Recognition:
• Line: Limited (trends only)
• Bar: Moderate (OHLC patterns)
• Candlestick: Excellent (visual patterns)

Visual Clarity:
• Line: High (simple)
• Bar: Moderate (detailed)
• Candlestick: High (color-coded)
"""

# Create a second subplot for text
ax5 = fig.add_subplot(gs[1, 1])
ax5.axis('off')
ax5.text(0.05, 0.95, comparison_text, transform=ax5.transAxes, fontsize=10,
        verticalalignment='top', family='monospace',
        bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.6))

plt.tight_layout()
display(fig)
plt.close(fig)

Reversal Patterns

Reversal patterns are among the most important chart patterns because they signal potential turning points in the market. These patterns emerge when a prevailing trend is losing momentum and the market is preparing to change direction. Identifying reversal patterns early can provide significant trading opportunities, but they must be confirmed by other technical signals to avoid false signals.

Head and Shoulders

The head and shoulders pattern is one of the most reliable and widely recognized reversal patterns in technical analysis. It signals a potential trend reversal from bullish to bearish and is considered one of the strongest bearish reversal patterns.

Head and Shoulders Pattern: A bearish reversal pattern consisting of three peaks, where the middle peak (head) is higher than the two surrounding peaks (shoulders). The pattern is completed when price breaks below the neckline (support level connecting the two troughs between the peaks).

The psychology behind the head and shoulders pattern reveals the shifting balance between buyers and sellers. The first shoulder represents the peak of buying enthusiasm in an uptrend. After this peak, profit-taking creates the first trough, but the trend remains intact as buyers step in again. The head forms when buyers push prices to a new high, but this peak is often made on declining volume, suggesting waning buying interest. The second shoulder forms when buyers attempt to push prices higher again but fail to reach the head's level, indicating that buying power is exhausted. When price breaks below the neckline, it confirms that sellers have taken control and the trend has reversed.

The pattern's reliability comes from its clear structure: three peaks with the middle one being the highest, volume that typically declines on the head and second shoulder, and a neckline that, when broken, confirms the reversal. The price target for a head and shoulders pattern is typically the distance from the head to the neckline, projected downward from the neckline break.

Python exercise

#| label: fig-head-shoulders-pattern
#| fig-cap: "Head and Shoulders Pattern: Enhanced Analysis - Volume, Confirmation, and Price Target"
#| fig-width: 18
#| fig-height: 12

# Sandbox metadata (auto-generated from lesson.ts)
# libraries: numpy, matplotlib, pandas

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
from datetime import datetime, timedelta
from IPython.display import display

# Generate head and shoulders pattern data with volume
np.random.seed(42)

# Create the pattern
prices = []
volumes = []
base_volume = 1000000

# Left shoulder - high volume
for i in range(10):
    prices.append(100 + i * 2 + np.random.normal(0, 0.5))
    volumes.append(base_volume * 1.5 + np.random.normal(0, 100000))
# Decline to neckline - decreasing volume
for i in range(5):
    prices.append(prices[-1] - 1.5 + np.random.normal(0, 0.5))
    volumes.append(base_volume * 0.8 + np.random.normal(0, 80000))
# Head - lower volume than left shoulder (bearish sign)
for i in range(10):
    prices.append(prices[-1] + 2.5 + np.random.normal(0, 0.5))
    volumes.append(base_volume * 1.2 + np.random.normal(0, 90000))
for i in range(5):
    prices.append(prices[-1] - 1.5 + np.random.normal(0, 0.5))
    volumes.append(base_volume * 0.7 + np.random.normal(0, 70000))
# Right shoulder - even lower volume (weakness)
for i in range(10):
    prices.append(prices[-1] + 1.5 + np.random.normal(0, 0.5))
    volumes.append(base_volume * 1.0 + np.random.normal(0, 80000))
for i in range(5):
    prices.append(prices[-1] - 1.5 + np.random.normal(0, 0.5))
    volumes.append(base_volume * 0.9 + np.random.normal(0, 70000))
# Neckline break - high volume (confirmation)
for i in range(15):
    prices.append(prices[-1] - 2 + np.random.normal(0, 0.5))
    if i < 3:
        volumes.append(base_volume * 2.0 + np.random.normal(0, 150000))  # High volume on break
    else:
        volumes.append(base_volume * 1.3 + np.random.normal(0, 100000))

# Create dates to match prices length (60 elements: 10+5+10+5+10+5+15)
dates = [datetime(2024, 1, 1) + timedelta(days=i) for i in range(len(prices))]

# Identify key points
left_shoulder_idx = 10
neckline1_idx = 15
head_idx = 25
neckline2_idx = 30
right_shoulder_idx = 40
neckline_break_idx = 45

# Calculate neckline
neckline_level = min(prices[neckline1_idx], prices[neckline2_idx])
head_height = prices[head_idx] - neckline_level
target_price = neckline_level - head_height

# Create 4-panel figure
fig = plt.figure(figsize=(18, 12))
gs = fig.add_gridspec(3, 2, hspace=0.35, wspace=0.3, height_ratios=[2, 1, 1])
fig.suptitle('Head and Shoulders Pattern: Enhanced Analysis - Volume, Confirmation, and Price Target', 
             fontsize=17, fontweight='bold', y=0.98)

# Panel 1: Price Pattern with Annotations
ax1 = fig.add_subplot(gs[0, :])
ax1.plot(dates, prices, color='#2E86AB', linewidth=2.5, label='Price Action', alpha=0.9, zorder=3)

# Draw neckline
neckline_x = [dates[neckline1_idx], dates[neckline2_idx]]
neckline_y = [neckline_level, neckline_level]
ax1.plot(neckline_x, neckline_y, '--', color='red', linewidth=2.5, label='Neckline (Support)', alpha=0.8)
ax1.plot([dates[neckline2_idx], dates[-1]], [neckline_level, neckline_level], '--', 
        color='red', linewidth=1.5, alpha=0.5)

# Annotate pattern components
ax1.annotate('Left Shoulder', xy=(dates[left_shoulder_idx], prices[left_shoulder_idx]),
            xytext=(15, 25), textcoords='offset points', fontsize=10, fontweight='bold',
            bbox=dict(boxstyle='round', facecolor='yellow', alpha=0.8),
            arrowprops=dict(arrowstyle='->', color='black', lw=1.5))
ax1.annotate('Head\n(Highest Peak)', xy=(dates[head_idx], prices[head_idx]),
            xytext=(15, 35), textcoords='offset points', fontsize=10, fontweight='bold',
            bbox=dict(boxstyle='round', facecolor='orange', alpha=0.8),
            arrowprops=dict(arrowstyle='->', color='black', lw=1.5))
ax1.annotate('Right Shoulder\n(Lower than Head)', xy=(dates[right_shoulder_idx], prices[right_shoulder_idx]),
            xytext=(15, 25), textcoords='offset points', fontsize=10, fontweight='bold',
            bbox=dict(boxstyle='round', facecolor='yellow', alpha=0.8),
            arrowprops=dict(arrowstyle='->', color='black', lw=1.5))
ax1.annotate('Neckline Break\n(Reversal Confirmed)', 
            xy=(dates[neckline_break_idx], prices[neckline_break_idx]),
            xytext=(15, -45), textcoords='offset points', fontsize=11, fontweight='bold',
            bbox=dict(boxstyle='round', facecolor='red', alpha=0.9),
            arrowprops=dict(arrowstyle='->', color='red', lw=2.5))

# Price target
ax1.plot([dates[neckline_break_idx], dates[-1]], [neckline_level, target_price], 
        '--', color='green', linewidth=2.5, alpha=0.7, label=f'Price Target: ${target_price:.2f}')
ax1.text(dates[-1], target_price, f'Target: ${target_price:.2f}', 
        fontsize=10, fontweight='bold', va='bottom',
        bbox=dict(boxstyle='round', facecolor='lightgreen', alpha=0.8))

ax1.set_title('Panel 1: Head and Shoulders Pattern - Bearish Reversal Formation', 
              fontsize=13, fontweight='bold')
ax1.set_ylabel('Price ($)', fontsize=11, fontweight='bold')
ax1.legend(loc='upper left', fontsize=9)
ax1.grid(True, alpha=0.3, linestyle='--')
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%b %d'))

# Panel 2: Volume Analysis
ax2 = fig.add_subplot(gs[1, 0])
ax2.bar([mdates.date2num(d) for d in dates], volumes, width=0.8, 
        color=['#2ecc71' if prices[i] > prices[i-1] else '#e74c3c' for i in range(1, len(prices))] + ['gray'],
        alpha=0.6, edgecolor='black', linewidth=0.5)

# Highlight key volume points
ax2.axvline(mdates.date2num(dates[left_shoulder_idx]), color='yellow', linestyle='--', 
            linewidth=2, alpha=0.7, label='Left Shoulder')
ax2.axvline(mdates.date2num(dates[head_idx]), color='orange', linestyle='--', 
            linewidth=2, alpha=0.7, label='Head')
ax2.axvline(mdates.date2num(dates[right_shoulder_idx]), color='yellow', linestyle='--', 
            linewidth=2, alpha=0.7, label='Right Shoulder')
ax2.axvline(mdates.date2num(dates[neckline_break_idx]), color='red', linestyle='--', 
            linewidth=2, alpha=0.7, label='Neckline Break')

ax2.set_title('Panel 2: Volume Analysis - Declining Volume on Head & Right Shoulder', 
              fontsize=12, fontweight='bold')
ax2.set_ylabel('Volume', fontsize=11, fontweight='bold')
ax2.legend(loc='upper left', fontsize=8, ncol=2)
ax2.grid(True, alpha=0.3, linestyle='--')
ax2.xaxis.set_major_formatter(mdates.DateFormatter('%b %d'))

# Panel 3: Pattern Characteristics
ax3 = fig.add_subplot(gs[1, 1])
ax3.axis('off')

# Calculate pattern metrics
left_shoulder_vol = np.mean(volumes[left_shoulder_idx-2:left_shoulder_idx+3])
head_vol = np.mean(volumes[head_idx-2:head_idx+3])
right_shoulder_vol = np.mean(volumes[right_shoulder_idx-2:right_shoulder_idx+3])
break_vol = np.mean(volumes[neckline_break_idx:neckline_break_idx+3])

volume_ratio_head = head_vol / left_shoulder_vol
volume_ratio_shoulder = right_shoulder_vol / left_shoulder_vol
volume_ratio_break = break_vol / left_shoulder_vol

pattern_text = f"""
Head and Shoulders Pattern Characteristics:

Pattern Structure:
• Left Shoulder: Peak at ${prices[left_shoulder_idx]:.2f}
• Head: Highest peak at ${prices[head_idx]:.2f}
• Right Shoulder: Lower peak at ${prices[right_shoulder_idx]:.2f}
• Neckline: Support at ${neckline_level:.2f}

Volume Analysis:
• Left Shoulder Volume: {left_shoulder_vol/1000:.0f}K
• Head Volume: {head_vol/1000:.0f}K ({volume_ratio_head:.2f}x)
• Right Shoulder Volume: {right_shoulder_vol/1000:.0f}K ({volume_ratio_shoulder:.2f}x)
• Break Volume: {break_vol/1000:.0f}K ({volume_ratio_break:.2f}x)

Pattern Metrics:
• Head Height: ${head_height:.2f}
• Price Target: ${target_price:.2f}
• Target Distance: ${abs(target_price - neckline_level):.2f}

Confirmation Signals:
✓ Right shoulder lower than head
✓ Declining volume pattern
✓ Neckline break with volume
✓ Target: Head height below neckline
"""

ax3.text(0.05, 0.95, pattern_text, transform=ax3.transAxes, fontsize=10,
        verticalalignment='top', family='monospace',
        bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.6))

# Panel 4: Trading Signals and Formula
ax4 = fig.add_subplot(gs[2, :])
ax4.axis('off')

formula_text = f"""
Head and Shoulders Pattern - Trading Guide

Pattern Formula:
Price Target = Neckline - (Head - Neckline)
Target = ${neckline_level:.2f} - ${head_height:.2f} = ${target_price:.2f}

Pattern Recognition:
1. Three peaks: Left shoulder, Head (highest), Right shoulder (lower)
2. Neckline connects the two troughs
3. Pattern completes on neckline break
4. Volume should decline on head and right shoulder
5. Volume should increase on neckline break

Trading Signals:
• Entry: Short on neckline break with volume
• Stop Loss: Above right shoulder peak (${prices[right_shoulder_idx]:.2f})
• Price Target: ${target_price:.2f} (${head_height:.2f} below neckline)
• Risk/Reward: Calculate based on entry and stop loss

Confirmation Requirements:
✓ Head must be highest peak
✓ Right shoulder lower than head
✓ Both shoulders similar height
✓ Volume declines on head/right shoulder
✓ Volume increases on break
✓ Minimum target distance = head height
"""

ax4.text(0.05, 0.95, formula_text, transform=ax4.transAxes, fontsize=10,
        verticalalignment='top', family='monospace',
        bbox=dict(boxstyle='round', facecolor='lightblue', alpha=0.6))

plt.tight_layout()
display(fig)
plt.close(fig)

Inverse Head and Shoulders: The inverse (or reverse) head and shoulders pattern is the bullish counterpart, signaling a potential trend reversal from bearish to bullish. It consists of three troughs, where the middle trough (head) is lower than the two surrounding troughs (shoulders), and the pattern is completed when price breaks above the neckline.

Double Tops and Double Bottoms

Double tops and double bottoms are simpler reversal patterns than head and shoulders but are equally important. They represent the market's failure to break through a key level twice, indicating exhaustion of the prevailing trend.

Double Top Pattern: A bearish reversal pattern consisting of two peaks at approximately the same price level, separated by a trough. The pattern is completed when price breaks below the trough (confirmation line), signaling that the uptrend has reversed.

The double top pattern forms when buyers attempt to push prices higher but fail at the same resistance level twice. The first peak represents the initial rejection of higher prices, while the second peak confirms that buyers lack the strength to break through. The trough between the peaks (the confirmation line) acts as support, and when this support is broken, it confirms that sellers have gained control.

The pattern's reliability increases when: (1) the two peaks are at approximately the same level, (2) volume is higher on the first peak than the second (indicating waning buying interest), (3) there's sufficient time between the peaks (allowing for market participation), and (4) the confirmation line break occurs on increased volume.

The price target for a double top is typically the distance from the peaks to the confirmation line, projected downward from the confirmation line break. This target represents the minimum expected decline after the reversal is confirmed.

Double Bottom Pattern: The double bottom is the bullish counterpart of the double top, consisting of two troughs at approximately the same price level, separated by a peak. The pattern is completed when price breaks above the peak (confirmation line), signaling a reversal from bearish to bullish.

Python exercise

#| label: fig-double-top-bottom-patterns
#| fig-cap: "Double Top and Double Bottom Patterns: Enhanced Analysis - Volume, Targets, and Confirmation"
#| fig-width: 18
#| fig-height: 12

# Sandbox metadata (auto-generated from lesson.ts)
# libraries: numpy, matplotlib, pandas

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
from datetime import datetime, timedelta
from IPython.display import display

# Create 4-panel figure
fig = plt.figure(figsize=(18, 12))
gs = fig.add_gridspec(3, 2, hspace=0.35, wspace=0.3, height_ratios=[2, 1, 1])
fig.suptitle('Double Top and Double Bottom Patterns: Enhanced Analysis - Volume, Targets, and Confirmation', 
             fontsize=17, fontweight='bold', y=0.98)

# Generate double top pattern data with volume
np.random.seed(42)
dates_top = [datetime(2024, 1, 1) + timedelta(days=i) for i in range(50)]
prices_top = []
volumes_top = []
base_volume = 1000000

# Uptrend to first peak - high volume
for i in range(10):
    prices_top.append(100 + i * 2 + np.random.normal(0, 0.5))
    volumes_top.append(base_volume * 1.8 + np.random.normal(0, 120000))
# Decline to trough - decreasing volume
for i in range(5):
    prices_top.append(prices_top[-1] - 2 + np.random.normal(0, 0.5))
    volumes_top.append(base_volume * 0.7 + np.random.normal(0, 70000))
# Rise to second peak - lower volume (bearish)
for i in range(10):
    prices_top.append(prices_top[-1] + 2 + np.random.normal(0, 0.5))
    volumes_top.append(base_volume * 1.2 + np.random.normal(0, 90000))
# Decline and break confirmation line - high volume on break
for i in range(25):
    prices_top.append(prices_top[-1] - 1.5 + np.random.normal(0, 0.5))
    if i < 3:
        volumes_top.append(base_volume * 2.2 + np.random.normal(0, 150000))
    else:
        volumes_top.append(base_volume * 1.4 + np.random.normal(0, 100000))

# Identify key levels for double top
peak1_idx = 10
trough_idx = 15
peak2_idx = 25
break_idx = 35

peak_level = prices_top[peak1_idx]
trough_level = prices_top[trough_idx]
target_top = trough_level - (peak_level - trough_level)
pattern_height = peak_level - trough_level

# Panel 1: Double Top Pattern
ax1 = fig.add_subplot(gs[0, 0])
ax1.plot(dates_top, prices_top, color='#2E86AB', linewidth=2.5, label='Price Action', alpha=0.9, zorder=3)

# Draw resistance line
ax1.plot([dates_top[peak1_idx], dates_top[peak2_idx]], [peak_level, peak_level], 
         '--', color='red', linewidth=2.5, label='Resistance Level', alpha=0.8)
# Draw confirmation line
ax1.plot([dates_top[trough_idx], dates_top[-1]], [trough_level, trough_level], 
         '--', color='orange', linewidth=2.5, label='Confirmation Line', alpha=0.8)

# Annotate
ax1.annotate('First Peak\n(High Volume)', xy=(dates_top[peak1_idx], prices_top[peak1_idx]),
            xytext=(15, 25), textcoords='offset points', fontsize=9, fontweight='bold',
            bbox=dict(boxstyle='round', facecolor='yellow', alpha=0.8),
            arrowprops=dict(arrowstyle='->', color='black', lw=1.5))
ax1.annotate('Second Peak\n(Lower Volume)', xy=(dates_top[peak2_idx], prices_top[peak2_idx]),
            xytext=(15, 25), textcoords='offset points', fontsize=9, fontweight='bold',
            bbox=dict(boxstyle='round', facecolor='yellow', alpha=0.8),
            arrowprops=dict(arrowstyle='->', color='black', lw=1.5))
ax1.annotate('Break Below\nConfirmation', xy=(dates_top[break_idx], prices_top[break_idx]),
            xytext=(15, -35), textcoords='offset points', fontsize=10, fontweight='bold',
            bbox=dict(boxstyle='round', facecolor='red', alpha=0.9),
            arrowprops=dict(arrowstyle='->', color='red', lw=2.5))

# Price target
ax1.plot([dates_top[break_idx], dates_top[-1]], [trough_level, target_top], 
         '--', color='green', linewidth=2.5, alpha=0.7, label=f'Target: ${target_top:.2f}')
ax1.text(dates_top[-1], target_top, f'Target: ${target_top:.2f}', 
         fontsize=10, fontweight='bold', va='bottom',
         bbox=dict(boxstyle='round', facecolor='lightgreen', alpha=0.8))

ax1.set_title('Panel 1: Double Top Pattern (Bearish Reversal)', fontsize=13, fontweight='bold')
ax1.set_ylabel('Price ($)', fontsize=11, fontweight='bold')
ax1.legend(loc='upper left', fontsize=8)
ax1.grid(True, alpha=0.3, linestyle='--')
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%b %d'))

# Generate double bottom pattern data with volume
dates_bottom = [datetime(2024, 1, 1) + timedelta(days=i) for i in range(50)]
prices_bottom = []
volumes_bottom = []

# Downtrend to first trough - high volume
for i in range(10):
    prices_bottom.append(100 - i * 2 + np.random.normal(0, 0.5))
    volumes_bottom.append(base_volume * 1.8 + np.random.normal(0, 120000))
# Rise to peak - decreasing volume
for i in range(5):
    prices_bottom.append(prices_bottom[-1] + 2 + np.random.normal(0, 0.5))
    volumes_bottom.append(base_volume * 0.7 + np.random.normal(0, 70000))
# Decline to second trough - lower volume (bullish)
for i in range(10):
    prices_bottom.append(prices_bottom[-1] - 2 + np.random.normal(0, 0.5))
    volumes_bottom.append(base_volume * 1.2 + np.random.normal(0, 90000))
# Rise and break confirmation line - high volume on break
for i in range(25):
    prices_bottom.append(prices_bottom[-1] + 1.5 + np.random.normal(0, 0.5))
    if i < 3:
        volumes_bottom.append(base_volume * 2.2 + np.random.normal(0, 150000))
    else:
        volumes_bottom.append(base_volume * 1.4 + np.random.normal(0, 100000))

# Identify key levels for double bottom
trough1_idx = 10
peak_idx = 15
trough2_idx = 25
break_idx_bottom = 35

trough_level = prices_bottom[trough1_idx]
peak_level = prices_bottom[peak_idx]
target_bottom = peak_level + (peak_level - trough_level)

# Panel 2: Double Bottom Pattern
ax2 = fig.add_subplot(gs[0, 1])
ax2.plot(dates_bottom, prices_bottom, color='#2E86AB', linewidth=2.5, label='Price Action', alpha=0.9, zorder=3)

# Draw support line
ax2.plot([dates_bottom[trough1_idx], dates_bottom[trough2_idx]], [trough_level, trough_level], 
         '--', color='green', linewidth=2.5, label='Support Level', alpha=0.8)
# Draw confirmation line
ax2.plot([dates_bottom[peak_idx], dates_bottom[-1]], [peak_level, peak_level], 
         '--', color='orange', linewidth=2.5, label='Confirmation Line', alpha=0.8)

# Annotate
ax2.annotate('First Trough\n(High Volume)', xy=(dates_bottom[trough1_idx], prices_bottom[trough1_idx]),
            xytext=(15, -35), textcoords='offset points', fontsize=9, fontweight='bold',
            bbox=dict(boxstyle='round', facecolor='lightblue', alpha=0.8),
            arrowprops=dict(arrowstyle='->', color='black', lw=1.5))
ax2.annotate('Second Trough\n(Lower Volume)', xy=(dates_bottom[trough2_idx], prices_bottom[trough2_idx]),
            xytext=(15, -35), textcoords='offset points', fontsize=9, fontweight='bold',
            bbox=dict(boxstyle='round', facecolor='lightblue', alpha=0.8),
            arrowprops=dict(arrowstyle='->', color='black', lw=1.5))
ax2.annotate('Break Above\nConfirmation', xy=(dates_bottom[break_idx_bottom], prices_bottom[break_idx_bottom]),
            xytext=(15, 35), textcoords='offset points', fontsize=10, fontweight='bold',
            bbox=dict(boxstyle='round', facecolor='green', alpha=0.9),
            arrowprops=dict(arrowstyle='->', color='green', lw=2.5))

# Price target
ax2.plot([dates_bottom[break_idx_bottom], dates_bottom[-1]], [peak_level, target_bottom], 
         '--', color='green', linewidth=2.5, alpha=0.7, label=f'Target: ${target_bottom:.2f}')
ax2.text(dates_bottom[-1], target_bottom, f'Target: ${target_bottom:.2f}', 
         fontsize=10, fontweight='bold', va='bottom',
         bbox=dict(boxstyle='round', facecolor='lightgreen', alpha=0.8))

ax2.set_title('Panel 2: Double Bottom Pattern (Bullish Reversal)', fontsize=13, fontweight='bold')
ax2.set_ylabel('Price ($)', fontsize=11, fontweight='bold')
ax2.legend(loc='upper left', fontsize=8)
ax2.grid(True, alpha=0.3, linestyle='--')
ax2.xaxis.set_major_formatter(mdates.DateFormatter('%b %d'))

# Panel 3: Volume Analysis Comparison
ax3 = fig.add_subplot(gs[1, :])
# Normalize volumes for comparison
volumes_top_norm = [v / max(volumes_top) * 100 for v in volumes_top]
volumes_bottom_norm = [v / max(volumes_bottom) * 100 for v in volumes_bottom]

x_pos = np.arange(len(dates_top))
width = 0.35

ax3_twin = ax3.twinx()
bars1 = ax3.bar([x - width/2 for x in x_pos], volumes_top_norm, width, 
                label='Double Top Volume', color='red', alpha=0.6, edgecolor='black')
bars2 = ax3_twin.bar([x + width/2 for x in x_pos], volumes_bottom_norm, width,
                     label='Double Bottom Volume', color='green', alpha=0.6, edgecolor='black')

# Highlight key points
ax3.axvline(x=peak1_idx, color='yellow', linestyle='--', linewidth=2, alpha=0.7, label='Peak 1')
ax3.axvline(x=peak2_idx, color='orange', linestyle='--', linewidth=2, alpha=0.7, label='Peak 2')
ax3.axvline(x=break_idx, color='red', linestyle='--', linewidth=2, alpha=0.7, label='Break')

ax3.set_title('Panel 3: Volume Analysis - Declining Volume on Second Peak/Trough', 
              fontsize=12, fontweight='bold')
ax3.set_xlabel('Days', fontsize=11, fontweight='bold')
ax3.set_ylabel('Double Top Volume (Normalized %)', fontsize=11, fontweight='bold', color='red')
ax3_twin.set_ylabel('Double Bottom Volume (Normalized %)', fontsize=11, fontweight='bold', color='green')
ax3.set_xticks(x_pos[::5])
ax3.set_xticklabels([d.strftime('%b %d') for d in dates_top[::5]], rotation=45)
ax3.legend(loc='upper left', fontsize=8)
ax3_twin.legend(loc='upper right', fontsize=8)
ax3.grid(True, alpha=0.3, linestyle='--')

# Panel 4: Pattern Characteristics and Formulas
ax4 = fig.add_subplot(gs[2, :])
ax4.axis('off')

# Calculate volume ratios
peak1_vol = np.mean(volumes_top[peak1_idx-2:peak1_idx+3])
peak2_vol = np.mean(volumes_top[peak2_idx-2:peak2_idx+3])
break_vol_top = np.mean(volumes_top[break_idx:break_idx+3])
vol_ratio = peak2_vol / peak1_vol

trough1_vol = np.mean(volumes_bottom[trough1_idx-2:trough1_idx+3])
trough2_vol = np.mean(volumes_bottom[trough2_idx-2:trough2_idx+3])
break_vol_bottom = np.mean(volumes_bottom[break_idx_bottom:break_idx_bottom+3])
vol_ratio_bottom = trough2_vol / trough1_vol

formula_text = f"""
Double Top and Double Bottom Pattern Analysis

Pattern Formulas:
Double Top Target = Confirmation Line - (Peak - Confirmation Line)
                  = ${trough_level:.2f} - ${pattern_height:.2f} = ${target_top:.2f}

Double Bottom Target = Confirmation Line + (Confirmation Line - Trough)
                     = ${peak_level:.2f} + ${abs(peak_level - trough_level):.2f} = ${target_bottom:.2f}

Double Top Characteristics:
• Peak 1: ${peak_level:.2f} (Volume: {peak1_vol/1000:.0f}K)
• Peak 2: ${peak_level:.2f} (Volume: {peak2_vol/1000:.0f}K, {vol_ratio:.2f}x Peak 1)
• Confirmation Line: ${trough_level:.2f}
• Break Volume: {break_vol_top/1000:.0f}K ({break_vol_top/peak1_vol:.2f}x Peak 1)
• Pattern Height: ${pattern_height:.2f}
• Price Target: ${target_top:.2f}

Double Bottom Characteristics:
• Trough 1: ${trough_level:.2f} (Volume: {trough1_vol/1000:.0f}K)
• Trough 2: ${trough_level:.2f} (Volume: {trough2_vol/1000:.0f}K, {vol_ratio_bottom:.2f}x Trough 1)
• Confirmation Line: ${peak_level:.2f}
• Break Volume: {break_vol_bottom/1000:.0f}K ({break_vol_bottom/trough1_vol:.2f}x Trough 1)
• Pattern Height: ${abs(peak_level - trough_level):.2f}
• Price Target: ${target_bottom:.2f}

Confirmation Signals:
✓ Two peaks/troughs at similar levels
✓ Lower volume on second peak/trough (exhaustion)
✓ Higher volume on confirmation line break
✓ Minimum target = pattern height distance
"""

ax4.text(0.05, 0.95, formula_text, transform=ax4.transAxes, fontsize=10,
        verticalalignment='top', family='monospace',
        bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.6))

plt.tight_layout()
display(fig)
plt.close(fig)

Triple Tops and Triple Bottoms

Triple tops and triple bottoms are extensions of double tops and bottoms, representing the market's third failed attempt to break through a key level. These patterns are generally considered more reliable than double patterns because they require three failed attempts, providing stronger confirmation of trend exhaustion.

Triple Top Pattern: A bearish reversal pattern consisting of three peaks at approximately the same price level, separated by two troughs. The pattern is completed when price breaks below the lower of the two troughs (confirmation line), signaling that the uptrend has definitively reversed.

The triple top pattern demonstrates even stronger resistance than a double top. The first peak represents initial selling pressure, the second peak shows that buyers couldn't overcome resistance, and the third peak confirms complete exhaustion of buying power. The declining volume on each successive peak is a key confirmation signal, showing that fewer traders are participating in the buying attempts.

Rounded Tops and Bottoms

Rounded tops and bottoms (also called saucer patterns) represent gradual trend reversals that occur over extended periods. Unlike sharp reversal patterns like head and shoulders, rounded patterns show a slow, gradual shift in supply and demand.

Rounded Top Pattern: A bearish reversal pattern characterized by a gradual, rounded peak formation where prices rise slowly, reach a peak, and then decline slowly in a symmetrical curve. The pattern indicates a slow shift from bullish to bearish sentiment.

Rounded patterns are particularly useful for identifying major trend changes in longer timeframes. They represent the gradual exhaustion of a trend rather than sudden reversals, making them valuable for position traders and investors who focus on longer-term trends.

Continuation Patterns

Continuation patterns signal that the current trend is pausing to consolidate before resuming in the same direction. These patterns are essential for traders who want to add to positions or enter new positions in the direction of the prevailing trend. Understanding continuation patterns helps traders avoid premature exits and identify optimal entry points.

Triangles (Ascending, Descending, Symmetrical)

Triangles are among the most common continuation patterns and are formed by converging trendlines. They represent a period of consolidation where supply and demand are in balance, preparing for the next directional move.

Triangle Pattern: A continuation pattern formed by converging trendlines, representing a period of consolidation before the trend resumes. Triangles can be ascending (bullish), descending (bearish), or symmetrical (neutral), depending on the slope of the trendlines.

Ascending Triangle: An ascending triangle is a bullish continuation pattern characterized by a horizontal resistance line and an ascending support line. The pattern indicates that buyers are becoming more aggressive (the support line rises) while sellers maintain their price level (the resistance line is flat). The breakout typically occurs to the upside, continuing the prior uptrend.

Descending Triangle: A descending triangle is a bearish continuation pattern characterized by a horizontal support line and a descending resistance line. The pattern indicates that sellers are becoming more aggressive (the resistance line falls) while buyers maintain their price level (the support line is flat). The breakout typically occurs to the downside, continuing the prior downtrend.

Symmetrical Triangle: A symmetrical triangle is formed by both an ascending support line and a descending resistance line, creating a converging pattern. The pattern indicates that both buyers and sellers are becoming less aggressive, creating a period of indecision. The breakout direction is typically in the direction of the prior trend, but confirmation is essential.

Python exercise

#| label: fig-triangle-patterns
#| fig-cap: "Triangle Patterns: Enhanced Analysis - Breakout Detection, Volume Confirmation, and Price Targets"
#| fig-width: 18
#| fig-height: 12

# Sandbox metadata (auto-generated from lesson.ts)
# libraries: numpy, matplotlib, pandas

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.patches import Rectangle
import numpy as np
from datetime import datetime, timedelta
from IPython.display import display

# Create 4-panel figure
fig = plt.figure(figsize=(18, 12))
gs = fig.add_gridspec(2, 2, hspace=0.35, wspace=0.3, height_ratios=[1, 1])
fig.suptitle('Triangle Patterns: Enhanced Analysis - Breakout Detection, Volume Confirmation, and Price Targets', 
             fontsize=17, fontweight='bold', y=0.98)

# Generate ascending triangle data with volume
np.random.seed(42)
dates = [datetime(2024, 1, 1) + timedelta(days=i) for i in range(40)]

# Ascending triangle: flat top, rising bottom
prices_asc = []
volumes_asc = []
base_volume = 1000000
base = 100
resistance = 110
breakout_idx = 30

for i in range(40):
    support = base + i * 0.25
    amplitude = (resistance - support) * (1 - min(i/breakout_idx, 1)) * 0.8
    mid_price = (support + resistance) / 2
    if i < breakout_idx:
        price = mid_price + amplitude * np.sin(i/3) + np.random.normal(0, 0.3)
        volumes_asc.append(base_volume * (1.0 - i/breakout_idx * 0.3) + np.random.normal(0, 80000))
    else:  # Breakout
        price = resistance + (i - breakout_idx) * 0.8 + np.random.normal(0, 0.4)
        if i == breakout_idx:
            volumes_asc.append(base_volume * 2.5 + np.random.normal(0, 150000))
        else:
            volumes_asc.append(base_volume * 1.5 + np.random.normal(0, 100000))
    prices_asc.append(max(price, support * 0.98))

# Calculate triangle metrics
pattern_height = resistance - (base + 0.25 * (breakout_idx - 1))
target_price = resistance + pattern_height

# Panel 1: Ascending Triangle with Breakout
ax1 = fig.add_subplot(gs[0, 0])
dates_plot = dates
ax1.plot(dates_plot, prices_asc, color='#2E86AB', linewidth=2.5, label='Price', alpha=0.9, zorder=3)

# Draw triangle lines
ax1.plot([dates_plot[0], dates_plot[breakout_idx-1]], [resistance, resistance], 
         '--', color='red', linewidth=2.5, label='Resistance (Flat)', alpha=0.8)
support_line = [base + i * 0.25 for i in range(breakout_idx)]
ax1.plot(dates_plot[:breakout_idx], support_line, '--', color='green', linewidth=2.5, 
        label='Support (Ascending)', alpha=0.8)

# Highlight breakout
ax1.plot(dates_plot[breakout_idx:], prices_asc[breakout_idx:], color='green', linewidth=3, 
         alpha=0.8, label='Breakout', zorder=4)

# Price target
ax1.plot([dates_plot[breakout_idx], dates_plot[-1]], [resistance, target_price], 
         '--', color='orange', linewidth=2.5, alpha=0.7, label=f'Target: ${target_price:.2f}')
ax1.text(dates_plot[-1], target_price, f'Target', fontsize=9, fontweight='bold',
         bbox=dict(boxstyle='round', facecolor='lightgreen', alpha=0.8))

ax1.annotate('Breakout\n(High Volume)', 
            xy=(dates_plot[breakout_idx], prices_asc[breakout_idx]), xytext=(15, 25),
            textcoords='offset points', fontsize=10, fontweight='bold',
            bbox=dict(boxstyle='round', facecolor='green', alpha=0.8),
            arrowprops=dict(arrowstyle='->', color='green', lw=2.5))

ax1.set_title('Panel 1: Ascending Triangle (Bullish Continuation)', fontsize=13, fontweight='bold')
ax1.set_ylabel('Price ($)', fontsize=11, fontweight='bold')
ax1.legend(loc='upper left', fontsize=8)
ax1.grid(True, alpha=0.3, linestyle='--')
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%b %d'))

# Panel 2: Volume Analysis
ax2 = fig.add_subplot(gs[0, 1])
ax2.bar([mdates.date2num(d) for d in dates_plot], volumes_asc, width=0.8,
        color=['#2ecc71' if prices_asc[i] > prices_asc[i-1] else '#e74c3c' 
               for i in range(1, len(prices_asc))] + ['gray'],
        alpha=0.6, edgecolor='black', linewidth=0.5)
ax2.axvline(mdates.date2num(dates_plot[breakout_idx]), color='green', linestyle='--', 
            linewidth=2.5, alpha=0.8, label='Breakout')

# Calculate volume ratios
pre_breakout_vol = np.mean(volumes_asc[breakout_idx-5:breakout_idx])
breakout_vol = volumes_asc[breakout_idx]
vol_ratio = breakout_vol / pre_breakout_vol

ax2.set_title(f'Panel 2: Volume Analysis - Breakout Volume: {vol_ratio:.2f}x Average', 
              fontsize=12, fontweight='bold')
ax2.set_ylabel('Volume', fontsize=11, fontweight='bold')
ax2.legend(loc='upper left', fontsize=8)
ax2.grid(True, alpha=0.3, linestyle='--')
ax2.xaxis.set_major_formatter(mdates.DateFormatter('%b %d'))

# Panel 3: Pattern Comparison
ax3 = fig.add_subplot(gs[1, 0])
triangle_types = ['Ascending\n(Bullish)', 'Descending\n(Bearish)', 'Symmetrical\n(Neutral)']
breakout_directions = ['Up', 'Down', 'Prior Trend']
reliability = [85, 80, 75]  # Percentage reliability

colors_comp = ['green', 'red', 'blue']
bars = ax3.bar(triangle_types, reliability, color=colors_comp, alpha=0.7, 
               edgecolor='black', linewidth=1.5)

for bar, rel, direction in zip(bars, reliability, breakout_directions):
    height = bar.get_height()
    ax3.text(bar.get_x() + bar.get_width()/2., height + 1,
            f'{rel}%\n{direction}', ha='center', va='bottom', fontsize=10, fontweight='bold')

ax3.set_title('Panel 3: Triangle Pattern Comparison - Reliability & Breakout Direction', 
              fontsize=12, fontweight='bold')
ax3.set_ylabel('Reliability (%)', fontsize=11, fontweight='bold')
ax3.set_ylim(0, 100)
ax3.grid(True, alpha=0.3, linestyle='--', axis='y')

# Panel 4: Triangle Formulas and Trading Guide
ax4 = fig.add_subplot(gs[1, 1])
ax4.axis('off')

formula_text = f"""
Triangle Pattern Analysis:

Pattern Types:
1. Ascending Triangle: Flat resistance, rising support
2. Descending Triangle: Flat support, falling resistance
3. Symmetrical Triangle: Both lines converge

Price Target Formula:
Target = Breakout Level + Pattern Height
Target = ${resistance:.2f} + ${pattern_height:.2f} = ${target_price:.2f}

Pattern Characteristics:
• Pattern Height: ${pattern_height:.2f}
• Breakout Level: ${resistance:.2f}
• Price Target: ${target_price:.2f}
• Breakout Volume: {vol_ratio:.2f}x pre-breakout average

Confirmation Requirements:
✓ Breakout with volume (2x+ average)
✓ Price closes beyond pattern boundary
✓ Breakout in direction of prior trend
✓ Pattern completes 2/3 to 3/4 of apex

Trading Signals:
• Entry: On breakout confirmation
• Stop Loss: Below pattern boundary
• Target: Pattern height distance
• Risk/Reward: Calculate based on entry

Pattern Reliability:
• Ascending: 85% (bullish)
• Descending: 80% (bearish)
• Symmetrical: 75% (neutral)
"""

ax4.text(0.05, 0.95, formula_text, transform=ax4.transAxes, fontsize=10,
        verticalalignment='top', family='monospace',
        bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.6))

plt.tight_layout()
display(fig)
plt.close(fig)

Flags and Pennants

Flags and pennants are short-term continuation patterns that form after strong directional moves. They represent brief consolidation periods before the trend resumes, making them excellent patterns for short-term traders.

Flag Pattern: A continuation pattern consisting of a sharp price move (the flagpole) followed by a small rectangular consolidation (the flag) that slopes against the trend. The pattern is completed when price breaks out of the flag in the direction of the original move.

Flags form when a strong directional move creates a "flagpole" - a sharp price movement on high volume. This is followed by a brief consolidation period where prices move in a narrow range, typically with declining volume. The flag portion slopes slightly against the trend direction, creating a rectangular or parallelogram shape. The breakout from the flag typically occurs in the direction of the original move, with the price target being the length of the flagpole projected from the flag breakout point.

Pennant Pattern: A pennant is similar to a flag but forms a small symmetrical triangle instead of a rectangle. Like flags, pennants follow strong directional moves and represent brief consolidation before the trend resumes.

Rectangles

Rectangles (also called trading ranges or boxes) are continuation patterns where prices move between parallel support and resistance levels. They represent periods of consolidation where supply and demand are balanced, typically before a breakout in the direction of the prior trend.

Rectangle Pattern: A continuation pattern formed by parallel horizontal support and resistance levels, creating a rectangular trading range. The pattern is completed when price breaks out of the rectangle in the direction of the prior trend.

Rectangles are particularly useful for identifying entry points because they provide clear support and resistance levels. Traders can buy near support and sell near resistance within the rectangle, or wait for the breakout to enter in the direction of the trend. The price target for a rectangle breakout is typically the height of the rectangle added to (for upward breakouts) or subtracted from (for downward breakouts) the breakout point.

Wedges

Wedges are similar to triangles but have both trendlines sloping in the same direction. They represent a gradual convergence of supply and demand, typically leading to a breakout in the opposite direction of the wedge slope.

Rising Wedge: A bearish pattern formed by two ascending trendlines that converge, with both lines sloping upward. Despite the upward slope, the pattern typically breaks down, signaling a reversal or continuation of a downtrend.

Falling Wedge: A bullish pattern formed by two descending trendlines that converge, with both lines sloping downward. Despite the downward slope, the pattern typically breaks up, signaling a reversal or continuation of an uptrend.

The key difference between wedges and triangles is the direction of both trendlines. In a triangle, one line is flat or the lines slope in opposite directions. In a wedge, both lines slope in the same direction, creating a different psychological dynamic that often leads to breakouts in the opposite direction.

Pattern Recognition and Trading

Successfully trading chart patterns requires more than just pattern recognition - it requires understanding pattern reliability, confirmation signals, and proper risk management. Not all patterns are created equal, and even the most reliable patterns can fail if not properly confirmed and managed.

Pattern Reliability Factors: Several factors affect pattern reliability: (1) Timeframe - patterns on longer timeframes are generally more reliable than those on shorter timeframes; (2) Volume confirmation - patterns with volume confirmation are more reliable than those without; (3) Pattern completion - waiting for pattern completion (confirmation) increases reliability; (4) Market context - patterns in trending markets are more reliable than those in choppy markets; (5) Pattern clarity - well-defined patterns are more reliable than ambiguous ones.

Confirmation Signals: Pattern recognition alone is not sufficient - confirmation is essential. Key confirmation signals include: (1) Volume confirmation - breakouts on increased volume are more reliable; (2) Price confirmation - waiting for price to close beyond the pattern boundary; (3) Time confirmation - patterns that take longer to form are often more reliable; (4) Multiple timeframe confirmation - patterns confirmed across multiple timeframes are stronger.

Risk Management: Even the most reliable patterns can fail, making risk management essential. Key principles include: (1) Stop losses - always place stops beyond pattern boundaries; (2) Position sizing - risk only a small percentage of capital on each pattern trade; (3) Target setting - use pattern-based targets but take profits at logical levels; (4) Pattern failure - exit immediately if a pattern fails to follow through.

Knowledge Check 8.1

A stock forms a pattern with three peaks where the middle peak is the highest, followed by a break below the support level connecting the two troughs. What pattern is this, and what does it signal?

A. Double top - bullish reversal
B. Head and shoulders - bearish reversal
C. Triple top - bearish continuation
D. Ascending triangle - bullish continuation

Click to reveal answer

B. Head and shoulders - bearish reversal

The description matches a head and shoulders pattern: three peaks with the middle one (head) being the highest, and a break below the neckline (support level connecting the troughs). This is a bearish reversal pattern that signals a potential trend change from bullish to bearish.

Practice Problem 8.1: Pattern Identification and Target Calculation

A stock forms a head and shoulders pattern with the following characteristics:

  • Left shoulder peak: $105
  • Head peak: $115
  • Right shoulder peak: $105
  • Neckline (support level): $95
  1. What is the price target if the neckline breaks?
  2. What volume pattern would confirm this reversal?
  3. At what point would you consider the pattern invalidated?
Click to reveal solution

Solution:

1. Price Target Calculation:

  • Head height: $115 - $95 = $20
  • Neckline level: $95
  • Price target: $95 - $20 = $75

The target is calculated by measuring the distance from the head to the neckline and projecting it downward from the neckline break.

2. Volume Confirmation:
The pattern would be confirmed by:

  • Declining volume on the head and right shoulder (compared to left shoulder)
  • Increased volume on the neckline break
  • This volume pattern shows waning buying interest and increasing selling pressure

3. Pattern Invalidation:
The pattern would be invalidated if:

  • Price breaks above the head peak ($115) before breaking the neckline
  • Price breaks above the right shoulder and continues higher
  • The pattern would also be less reliable if volume increases on the head and right shoulder

In Module 8: Technical Analysis for Equities

  1. Introduction
  2. 1. Introduction to Technical Analysis
  3. 2. Chart Patterns
  4. 3. Candlestick Patterns
  5. 4. Technical Indicators
  6. 5. Support and Resistance
  7. 6. Trend Analysis
  8. 7. Volume Analysis
  9. Advanced Technical Analysis
  10. End-of-Module Assessment