Introduction

30 minbeginner

Learning Objectives

By the end of this module, you will be able to:

  1. Understand the fundamental principles of technical analysis and how it differs from fundamental analysis
  2. Identify and interpret common chart patterns, understanding their predictive power and limitations
  3. Recognize and analyze candlestick patterns, understanding their significance for price action
  4. Calculate and apply key technical indicators, including moving averages, RSI, and MACD
  5. Identify support and resistance levels, understanding their role in price behavior and trading decisions
  6. Analyze trends and trend reversals, applying trend-following and contrarian strategies
  7. Integrate volume analysis with price action to confirm signals and identify divergences
  8. Apply technical analysis concepts to develop trading strategies and make informed trading decisions

1. Introduction to Technical Analysis

What is Technical Analysis?

Technical analysis is a method of evaluating securities by analyzing statistics generated by market activity, such as past prices and volume. Unlike fundamental analysis, which attempts to measure a security's intrinsic value by examining financial statements and economic factors, technical analysis focuses on the study of price action and market behavior. Technical analysts believe that all relevant information about a security is already reflected in its price, and that analyzing price patterns and trends can help predict future price movements.

Technical Analysis: A trading discipline employed to evaluate investments and identify trading opportunities by analyzing statistical trends gathered from trading activity, such as price movement and volume. Technical analysis assumes that market prices reflect all available information and that price movements follow patterns that can be identified and exploited.

The fundamental premise of technical analysis is that price action reflects the collective psychology of all market participants. When buyers and sellers interact in the market, their actions create patterns that technical analysts can identify and use to make trading decisions. These patterns repeat because human psychology - fear, greed, hope, and regret - tends to be consistent across time and markets.

Technical analysis is used by traders, investors, and portfolio managers across all asset classes - stocks, bonds, commodities, currencies, and derivatives. While it's often associated with short-term trading, technical analysis principles can also be applied to longer-term investment decisions. The key is understanding which tools and techniques are appropriate for different timeframes and market conditions.

The Philosophy of Technical Analysis

Technical analysis is built on several core philosophical principles that distinguish it from other approaches to market analysis. Understanding these principles is essential for applying technical analysis effectively and recognizing its strengths and limitations.

The first principle is that the market discounts everything. This means that all available information - earnings reports, economic data, news events, investor sentiment, and even future expectations - is already reflected in the current price. Technical analysts don't need to analyze why a stock is moving; they simply need to analyze how it's moving. This principle frees technical analysts from the need to process vast amounts of fundamental information and allows them to focus solely on price action.

The following visualization illustrates how the market discounts information - notice how price movements anticipate and react to news events, with all information eventually reflected in the price action:

Python exercise

#| label: fig-market-discounts-everything
#| fig-cap: "The Market Discounts Everything: Enhanced Analysis - Price, Volume, and Information Absorption"
#| 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 price data showing how market discounts information
np.random.seed(101)
dates = [datetime(2024, 1, 1) + timedelta(days=i) for i in range(60)]
base_price = 100
prices = [base_price]

# Create scenario: Stock with various information events
for i in range(59):
    if i < 10:
        # Normal trading
        change = np.random.normal(0, 0.5)
    elif i < 15:
        # Earnings announcement approaching - price starts moving up (anticipation)
        change = 0.3 + np.random.normal(0, 0.4)
    elif i == 15:
        # Earnings beat announced - sharp jump
        change = 5 + np.random.normal(0, 0.5)
    elif i < 20:
        # Post-earnings consolidation
        change = -0.1 + np.random.normal(0, 0.3)
    elif i < 30:
        # Normal trading
        change = np.random.normal(0, 0.4)
    elif i < 35:
        # Negative news rumor - price starts declining (discounting)
        change = -0.4 + np.random.normal(0, 0.3)
    elif i == 35:
        # Bad news confirmed - sharp drop
        change = -4 + np.random.normal(0, 0.5)
    elif i < 45:
        # Recovery phase
        change = 0.2 + np.random.normal(0, 0.3)
    else:
        # Normal trading - all information absorbed
        change = np.random.normal(0, 0.4)
    
    prices.append(max(prices[-1] + change, 80))

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

# Generate volume data (higher volume on news events)
volumes = []
base_volume = 1000000
for i in range(59):
    if i < 10:
        volumes.append(base_volume + np.random.normal(0, 100000))
    elif i < 15:
        # Anticipation - increasing volume
        volumes.append(base_volume * (1.2 + (i-10)/10) + np.random.normal(0, 150000))
    elif i == 15:
        # Earnings announcement - very high volume
        volumes.append(base_volume * 3.5 + np.random.normal(0, 200000))
    elif i < 20:
        volumes.append(base_volume * 1.5 + np.random.normal(0, 120000))
    elif i < 30:
        volumes.append(base_volume + np.random.normal(0, 100000))
    elif i < 35:
        # Negative news rumor - increasing volume
        volumes.append(base_volume * (1.2 + (i-30)/10) + np.random.normal(0, 150000))
    elif i == 35:
        # Bad news - very high volume
        volumes.append(base_volume * 3.8 + np.random.normal(0, 200000))
    elif i < 45:
        volumes.append(base_volume * 1.3 + np.random.normal(0, 120000))
    else:
        volumes.append(base_volume + np.random.normal(0, 100000))

# Calculate price changes
price_changes = [closes[i] - opens[i] for i in range(len(closes))]

# Create 4-panel figure
fig = plt.figure(figsize=(18, 12))
gs = fig.add_gridspec(3, 2, hspace=0.3, wspace=0.3, height_ratios=[2, 1, 1])
fig.suptitle('The Market Discounts Everything: Enhanced Analysis - Price, Volume, and Information Absorption', 
             fontsize=17, fontweight='bold', y=0.98)

dates_plot = dates[1:]

# Panel 1: Price Action with Candlesticks
ax1 = fig.add_subplot(gs[0, :])
for i in range(len(opens)):
    date = dates_plot[i]
    open_price = opens[i]
    close_price = closes[i]
    high_price = highs[i]
    low_price = lows[i]
    
    color = '#2ecc71' if close_price >= open_price else '#e74c3c'
    body_low = min(open_price, close_price)
    body_high = max(open_price, close_price)
    body_height = body_high - body_low
    
    # Draw wick
    ax1.plot([date, date], [low_price, high_price], color='black', linewidth=0.8, alpha=0.6)
    # Draw body
    if body_height > 0:
        rect = plt.Rectangle((mdates.date2num(date) - 0.3, body_low), 0.6, body_height, 
                            facecolor=color, edgecolor='black', linewidth=0.5, alpha=0.8)
        ax1.add_patch(rect)
    else:
        ax1.plot([date, date], [open_price, close_price], color='black', linewidth=2)

# Annotate key events
ax1.axvspan(mdates.date2num(dates_plot[10]), mdates.date2num(dates_plot[15]), 
            alpha=0.15, color='yellow', label='Earnings Anticipation')
ax1.annotate('Earnings Beat\nAnnounced', 
            xy=(mdates.date2num(dates_plot[15]), closes[15]),
            xytext=(mdates.date2num(dates_plot[15]), closes[15] + 4),
            arrowprops=dict(arrowstyle='->', color='green', lw=2.5),
            fontsize=11, fontweight='bold', color='green',
            bbox=dict(boxstyle='round', facecolor='lightgreen', alpha=0.9))

ax1.axvspan(mdates.date2num(dates_plot[30]), mdates.date2num(dates_plot[35]), 
            alpha=0.15, color='orange', label='Negative News Rumor')
ax1.annotate('Bad News\nConfirmed', 
            xy=(mdates.date2num(dates_plot[35]), closes[35]),
            xytext=(mdates.date2num(dates_plot[35]), closes[35] - 5),
            arrowprops=dict(arrowstyle='->', color='red', lw=2.5),
            fontsize=11, fontweight='bold', color='red',
            bbox=dict(boxstyle='round', facecolor='lightcoral', alpha=0.9))

ax1.axvspan(mdates.date2num(dates_plot[45]), mdates.date2num(dates_plot[-1]), 
            alpha=0.1, color='blue', label='All Information Absorbed')

# Add EMA(20) for trend
ema_period = 20
ema_values = []
for i in range(len(closes)):
    if i < ema_period - 1:
        ema_values.append(None)
    else:
        ema = np.mean(closes[i-ema_period+1:i+1])
        ema_values.append(ema)
ema_dates = dates_plot[ema_period-1:]
ema_plot = [v for v in ema_values if v is not None]
ax1.plot(ema_dates, ema_plot, color='blue', linewidth=2, linestyle='--', alpha=0.7, label='EMA(20)')

ax1.set_ylabel('Price ($)', fontsize=12, fontweight='bold')
ax1.set_title('Panel 1: Price Action - Notice Price Moves Before News (Anticipation)', 
              fontsize=13, fontweight='bold')
ax1.legend(loc='upper left', fontsize=10)
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_plot], volumes, width=0.8, 
        color=['#2ecc71' if c > o else '#e74c3c' for o, c in zip(opens, closes)], 
        alpha=0.6, edgecolor='black', linewidth=0.5)
ax2.axvline(mdates.date2num(dates_plot[15]), color='green', linestyle='--', linewidth=2, alpha=0.7, label='Earnings')
ax2.axvline(mdates.date2num(dates_plot[35]), color='red', linestyle='--', linewidth=2, alpha=0.7, label='Bad News')
ax2.set_ylabel('Volume', fontsize=11, fontweight='bold')
ax2.set_title('Panel 2: Volume Confirms Price Movements', fontsize=12, fontweight='bold')
ax2.legend(loc='upper left', fontsize=9)
ax2.grid(True, alpha=0.3, linestyle='--')
ax2.xaxis.set_major_formatter(mdates.DateFormatter('%b %d'))

# Panel 3: Price Change Analysis (Anticipation vs Confirmation)
ax3 = fig.add_subplot(gs[1, 1])
ax3.bar(range(len(price_changes)), price_changes, 
        color=['#2ecc71' if ch > 0 else '#e74c3c' for ch in price_changes], 
        alpha=0.7, edgecolor='black', linewidth=0.5)
ax3.axhline(y=0, color='black', linewidth=1, linestyle='-')
ax3.axvline(x=15, color='green', linestyle='--', linewidth=2, alpha=0.7)
ax3.axvline(x=35, color='red', linestyle='--', linewidth=2, alpha=0.7)
ax3.fill_between(range(10, 15), -10, 10, alpha=0.2, color='yellow', label='Anticipation')
ax3.fill_between(range(30, 35), -10, 10, alpha=0.2, color='orange', label='Anticipation')
ax3.set_xlabel('Days', fontsize=11, fontweight='bold')
ax3.set_ylabel('Daily Price Change ($)', fontsize=11, fontweight='bold')
ax3.set_title('Panel 3: Price Changes - Anticipation Before News Events', fontsize=12, fontweight='bold')
ax3.legend(loc='upper right', fontsize=9)
ax3.grid(True, alpha=0.3, linestyle='--')

# Panel 4: Information Absorption Timeline
ax4 = fig.add_subplot(gs[2, :])
events = [
    ('Day 10-15', 'Earnings\nAnticipation', 'yellow', 12.5, 0.8),
    ('Day 15', 'Earnings\nBeat', 'green', 15, 1.0),
    ('Day 20-30', 'Normal Trading', 'gray', 25, 0.5),
    ('Day 30-35', 'Negative\nNews Rumor', 'orange', 32.5, 0.8),
    ('Day 35', 'Bad News\nConfirmed', 'red', 35, 1.0),
    ('Day 45+', 'All Info\nAbsorbed', 'blue', 52, 0.6)
]
event_positions = [e[3] for e in events]
event_names = [e[1] for e in events]
event_colors = [e[2] for e in events]
event_heights = [e[4] for e in events]

for i, (pos, name, color, height) in enumerate(zip(event_positions, event_names, event_colors, event_heights)):
    ax4.barh(0, height, left=pos-height/2, height=0.4, color=color, alpha=0.7, 
             edgecolor='black', linewidth=1.5)
    ax4.text(pos, 0, name, ha='center', va='center', fontsize=10, fontweight='bold')

# Add arrows showing information flow
ax4.annotate('', xy=(15, 0), xytext=(10, 0.3), 
            arrowprops=dict(arrowstyle='->', color='green', lw=2))
ax4.annotate('', xy=(35, 0), xytext=(30, 0.3), 
            arrowprops=dict(arrowstyle='->', color='red', lw=2))

ax4.set_xlim(0, 60)
ax4.set_ylim(-0.5, 0.5)
ax4.set_xlabel('Days', fontsize=11, fontweight='bold')
ax4.set_title('Panel 4: Information Timeline - Market Discounts Information Over Time', 
              fontsize=12, fontweight='bold')
ax4.set_yticks([])
ax4.grid(True, alpha=0.3, axis='x')

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

This visualization demonstrates the core principle that the market discounts everything. Notice how:

  • Price anticipates news: Before the earnings announcement (day 15), price begins moving up in anticipation
  • Price reacts to confirmation: When news is confirmed, price moves sharply
  • Price absorbs all information: Eventually, all information is reflected in the price, and trading returns to normal
  • Technical analysts don't need to know why: The price action itself tells the story

The second principle is that price moves in trends. Technical analysts believe that once a trend is established, it's more likely to continue than to reverse. This is based on the observation that market psychology tends to persist - if investors are bullish, they typically remain bullish until something changes their sentiment. This principle underlies most trend-following strategies, which seek to identify and ride existing trends rather than predict reversals.

The following visualization demonstrates the three types of trends - uptrends, downtrends, and sideways trends - and how they persist until evidence of reversal appears:

Python exercise

#| label: fig-price-moves-in-trends
#| fig-cap: "Price Moves in Trends: Enhanced Analysis - Trend Types, Strength, and Persistence"
#| 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
from scipy import stats

# Generate three trend scenarios
np.random.seed(102)
dates = [datetime(2024, 1, 1) + timedelta(days=i) for i in range(90)]

# Scenario 1: Uptrend (higher highs, higher lows)
uptrend_prices = [100]
for i in range(89):
    # Create higher highs and higher lows
    base_change = 0.3 + (i / 89) * 0.2  # Increasing trend strength
    change = base_change + np.random.normal(0, 0.8)
    uptrend_prices.append(max(uptrend_prices[-1] + change, uptrend_prices[-1] * 0.99))

# Scenario 2: Downtrend (lower highs, lower lows)
downtrend_prices = [120]
for i in range(89):
    # Create lower highs and lower lows
    base_change = -0.3 - (i / 89) * 0.2  # Increasing trend strength
    change = base_change + np.random.normal(0, 0.8)
    downtrend_prices.append(min(downtrend_prices[-1] + change, downtrend_prices[-1] * 1.01))

# Scenario 3: Sideways trend (range-bound)
sideways_prices = [110]
for i in range(89):
    # Oscillate within range
    oscillation = np.sin(i * np.pi / 15) * 2
    change = oscillation + np.random.normal(0, 0.5)
    sideways_prices.append(max(min(sideways_prices[-1] + change, 115), 105))

# Calculate trend strength metrics (slope using linear regression)
def calculate_trend_strength(prices):
    x = np.arange(len(prices))
    slope, intercept, r_value, p_value, std_err = stats.linregress(x, prices)
    return slope, r_value**2  # R-squared indicates trend strength

uptrend_slope, uptrend_r2 = calculate_trend_strength(uptrend_prices)
downtrend_slope, downtrend_r2 = calculate_trend_strength(downtrend_prices)
sideways_slope, sideways_r2 = calculate_trend_strength(sideways_prices)

# Generate OHLC data for uptrend
uptrend_opens = [uptrend_prices[i] + np.random.normal(0, 0.3) for i in range(89)]
uptrend_closes = uptrend_prices[1:]
uptrend_highs = [max(o, c) + abs(np.random.normal(0, 0.6)) for o, c in zip(uptrend_opens, uptrend_closes)]
uptrend_lows = [min(o, c) - abs(np.random.normal(0, 0.6)) for o, c in zip(uptrend_opens, uptrend_closes)]

# Generate OHLC data for downtrend
downtrend_opens = [downtrend_prices[i] + np.random.normal(0, 0.3) for i in range(89)]
downtrend_closes = downtrend_prices[1:]
downtrend_highs = [max(o, c) + abs(np.random.normal(0, 0.6)) for o, c in zip(downtrend_opens, downtrend_closes)]
downtrend_lows = [min(o, c) - abs(np.random.normal(0, 0.6)) for o, c in zip(downtrend_opens, downtrend_closes)]

# Generate OHLC data for sideways
sideways_opens = [sideways_prices[i] + np.random.normal(0, 0.3) for i in range(89)]
sideways_closes = sideways_prices[1:]
sideways_highs = [max(o, c) + abs(np.random.normal(0, 0.6)) for o, c in zip(sideways_opens, sideways_closes)]
sideways_lows = [min(o, c) - abs(np.random.normal(0, 0.6)) for o, c in zip(sideways_opens, sideways_closes)]

# Helper function to plot candlesticks
def plot_candlesticks(ax, dates_plot, opens, closes, highs, lows):
    for i in range(len(opens)):
        date = dates_plot[i]
        open_price = opens[i]
        close_price = closes[i]
        high_price = highs[i]
        low_price = lows[i]
        
        color = '#2ecc71' if close_price >= open_price else '#e74c3c'
        body_low = min(open_price, close_price)
        body_high = max(open_price, close_price)
        body_height = body_high - body_low
        
        # Draw wick
        ax.plot([date, date], [low_price, high_price], color='black', linewidth=0.8, alpha=0.6)
        # Draw body
        if body_height > 0:
            rect = plt.Rectangle((mdates.date2num(date) - 0.3, body_low), 0.6, body_height, 
                                facecolor=color, edgecolor='black', linewidth=0.5, alpha=0.8)
            ax.add_patch(rect)
        else:
            ax.plot([date, date], [open_price, close_price], color='black', linewidth=2)

# Create 4-panel figure
fig = plt.figure(figsize=(18, 12))
gs = fig.add_gridspec(2, 2, hspace=0.35, wspace=0.3)
fig.suptitle('Price Moves in Trends: Enhanced Analysis - Trend Types, Strength, and Persistence', 
             fontsize=17, fontweight='bold', y=0.98)

dates_plot = dates[1:]

# Panel 1: Uptrend with Trendline and Moving Average
ax1 = fig.add_subplot(gs[0, 0])
plot_candlesticks(ax1, dates_plot, uptrend_opens, uptrend_closes, uptrend_highs, uptrend_lows)

# Add EMA(20)
ema_period = 20
ema_uptrend = []
for i in range(len(uptrend_closes)):
    if i < ema_period - 1:
        ema_uptrend.append(None)
    else:
        ema = np.mean(uptrend_closes[i-ema_period+1:i+1])
        ema_uptrend.append(ema)
ema_dates = dates_plot[ema_period-1:]
ema_plot_vals = [v for v in ema_uptrend if v is not None]
ax1.plot(ema_dates, ema_plot_vals, color='blue', linewidth=2.5, linestyle='--', 
         alpha=0.8, label=f'EMA(20) - Trend Strength: {uptrend_r2:.2%}')

# Draw support trendline
first_low_idx = 5
last_low_idx = len(uptrend_lows) - 5
ax1.plot([dates_plot[first_low_idx], dates_plot[last_low_idx]], 
        [uptrend_lows[first_low_idx], uptrend_lows[last_low_idx]],
        color='green', linestyle='--', linewidth=2.5, alpha=0.8, label='Support Trendline')

ax1.set_title('Panel 1: Uptrend - Higher Highs & Higher Lows', 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: Downtrend with Trendline
ax2 = fig.add_subplot(gs[0, 1])
plot_candlesticks(ax2, dates_plot, downtrend_opens, downtrend_closes, downtrend_highs, downtrend_lows)

# Add EMA(20)
ema_downtrend = []
for i in range(len(downtrend_closes)):
    if i < ema_period - 1:
        ema_downtrend.append(None)
    else:
        ema = np.mean(downtrend_closes[i-ema_period+1:i+1])
        ema_downtrend.append(ema)
ema_plot_vals2 = [v for v in ema_downtrend if v is not None]
ax2.plot(ema_dates, ema_plot_vals2, color='blue', linewidth=2.5, linestyle='--', 
         alpha=0.8, label=f'EMA(20) - Trend Strength: {downtrend_r2:.2%}')

# Draw resistance trendline
first_high_idx = 5
last_high_idx = len(downtrend_highs) - 5
ax2.plot([dates_plot[first_high_idx], dates_plot[last_high_idx]], 
        [downtrend_highs[first_high_idx], downtrend_highs[last_high_idx]],
        color='red', linestyle='--', linewidth=2.5, alpha=0.8, label='Resistance Trendline')

ax2.set_title('Panel 2: Downtrend - Lower Highs & Lower Lows', fontsize=13, fontweight='bold')
ax2.set_ylabel('Price ($)', fontsize=11, fontweight='bold')
ax2.legend(loc='upper right', fontsize=9)
ax2.grid(True, alpha=0.3, linestyle='--')
ax2.xaxis.set_major_formatter(mdates.DateFormatter('%b %d'))

# Panel 3: Sideways Trend with Support/Resistance
ax3 = fig.add_subplot(gs[1, 0])
plot_candlesticks(ax3, dates_plot, sideways_opens, sideways_closes, sideways_highs, sideways_lows)

# Draw support and resistance levels
ax3.axhline(y=115, color='red', linestyle='--', linewidth=2.5, alpha=0.8, label='Resistance at $115')
ax3.axhline(y=105, color='green', linestyle='--', linewidth=2.5, alpha=0.8, label='Support at $105')
ax3.axhspan(105, 115, alpha=0.15, color='blue', label='Trading Range')

# Add EMA(20) to show it's flat
ema_sideways = []
for i in range(len(sideways_closes)):
    if i < ema_period - 1:
        ema_sideways.append(None)
    else:
        ema = np.mean(sideways_closes[i-ema_period+1:i+1])
        ema_sideways.append(ema)
ema_plot_vals3 = [v for v in ema_sideways if v is not None]
ax3.plot(ema_dates, ema_plot_vals3, color='blue', linewidth=2.5, linestyle='--', 
         alpha=0.8, label=f'EMA(20) - Range-Bound (R²={sideways_r2:.2%})')

ax3.set_title('Panel 3: Sideways Trend - Range-Bound Trading', fontsize=13, fontweight='bold')
ax3.set_xlabel('Date', fontsize=11, fontweight='bold')
ax3.set_ylabel('Price ($)', fontsize=11, fontweight='bold')
ax3.legend(loc='upper left', fontsize=9)
ax3.grid(True, alpha=0.3, linestyle='--')
ax3.xaxis.set_major_formatter(mdates.DateFormatter('%b %d'))

# Panel 4: Trend Strength Comparison
ax4 = fig.add_subplot(gs[1, 1])
trend_names = ['Uptrend', 'Downtrend', 'Sideways']
trend_slopes = [uptrend_slope, downtrend_slope, abs(sideways_slope)]
trend_r2_values = [uptrend_r2, downtrend_r2, sideways_r2]
colors = ['#2ecc71', '#e74c3c', '#3498db']

bars1 = ax4.bar([x - 0.2 for x in range(3)], trend_slopes, 0.4, label='Slope (Price Change/Day)', 
                color=colors, alpha=0.7, edgecolor='black', linewidth=1.5)
bars2 = ax4.bar([x + 0.2 for x in range(3)], [r*100 for r in trend_r2_values], 0.4, 
                label='R² (Trend Strength %)', color=[c for c in colors], alpha=0.5, 
                edgecolor='black', linewidth=1.5)

# Add value labels on bars
for i, (bar1, bar2, slope, r2) in enumerate(zip(bars1, bars2, trend_slopes, trend_r2_values)):
    ax4.text(bar1.get_x() + bar1.get_width()/2, bar1.get_height() + 0.01,
            f'{slope:.3f}', ha='center', va='bottom', fontsize=9, fontweight='bold')
    ax4.text(bar2.get_x() + bar2.get_width()/2, bar2.get_height() + 1,
            f'{r2*100:.1f}%', ha='center', va='bottom', fontsize=9, fontweight='bold')

ax4.set_xlabel('Trend Type', fontsize=11, fontweight='bold')
ax4.set_ylabel('Value', fontsize=11, fontweight='bold')
ax4.set_title('Panel 4: Trend Strength Metrics - Slope & R² Comparison', fontsize=13, fontweight='bold')
ax4.set_xticks(range(3))
ax4.set_xticklabels(trend_names, fontsize=10, fontweight='bold')
ax4.legend(loc='upper right', fontsize=9)
ax4.grid(True, alpha=0.3, linestyle='--', axis='y')

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

This visualization demonstrates the three fundamental trend types:

  • Uptrend: Characterized by higher highs and higher lows, with a rising support trendline
  • Downtrend: Characterized by lower highs and lower lows, with a declining resistance trendline
  • Sideways Trend: Price oscillates within a defined range, with clear support and resistance levels

Notice how trends persist - once established, they continue until evidence of reversal appears, which is why trend-following strategies seek to ride existing trends rather than predict reversals.

The third principle is that history tends to repeat itself. Technical analysts believe that price patterns that have worked in the past will work in the future, because human psychology - which drives these patterns - doesn't change. This principle justifies the use of chart patterns and technical indicators that are based on historical price behavior. However, it's important to recognize that while patterns may be similar, they're never identical, and market conditions can change.

Technical Analysis vs. Fundamental Analysis

Technical analysis and fundamental analysis represent two distinct approaches to evaluating securities, each with different philosophies, methods, and timeframes. Understanding the differences between them helps you choose the appropriate approach for your investment style and objectives.

Fundamental Analysis focuses on determining a security's intrinsic value by examining financial statements, economic factors, industry conditions, and company management. Fundamental analysts believe that markets can misprice securities in the short run, but will eventually correct to reflect true value. They seek to buy undervalued securities and sell overvalued ones. Fundamental analysis is typically used for longer-term investment decisions, as it can take time for markets to recognize and correct pricing errors.

Technical Analysis focuses on analyzing price action and market behavior, assuming that all information is already reflected in the price. Technical analysts believe that price patterns and trends can predict future movements, regardless of fundamental factors. They seek to identify entry and exit points based on price action, volume, and technical indicators. Technical analysis is typically used for shorter-term trading decisions, as it focuses on timing rather than long-term value.

The two approaches are not mutually exclusive - many successful traders and investors combine both. For example, a fundamental analyst might use technical analysis to time entry into a fundamentally attractive stock, or a technical analyst might use fundamental analysis to filter out fundamentally weak stocks from consideration. The key is understanding when each approach is most appropriate and how to integrate them effectively.

Key Assumptions of Technical Analysis

Technical analysis is based on several key assumptions that, if accepted, justify the use of technical analysis methods. These assumptions are not universally accepted, and understanding them helps you recognize both the strengths and limitations of technical analysis.

Assumption 1: Market Prices Reflect All Available Information

This is the "efficient market" assumption in a weak form. Technical analysts believe that current prices incorporate all publicly available information, including fundamental factors, news, and investor sentiment. This assumption suggests that there's no need to analyze fundamentals separately - the price already tells you everything you need to know.

Assumption 2: Price Movements Follow Trends

Technical analysts assume that prices move in trends - upward, downward, or sideways - and that these trends persist until evidence of a reversal appears. This assumption underlies trend-following strategies and the use of moving averages and trendlines.

Assumption 3: History Repeats Itself

Technical analysts assume that price patterns that have occurred in the past will recur in the future, because the human psychology that drives these patterns is consistent. This assumption justifies the use of chart patterns and technical indicators based on historical analysis.

Assumption 4: Market Psychology Influences Price Action

Technical analysts believe that market prices are driven by the collective psychology of all participants - fear, greed, hope, and regret. These psychological factors create predictable patterns that can be identified and exploited.

Assumption 5: Price Action is More Important Than Why

Technical analysts focus on what is happening (price movement) rather than why it's happening (fundamental causes). This assumption allows technical analysts to make decisions based solely on price action without needing to understand underlying fundamentals.

Limitations and Criticisms

Technical analysis has several limitations and has been subject to significant criticism from both academics and practitioners. Understanding these limitations is crucial for applying technical analysis effectively and avoiding common pitfalls.

Criticism 1: Self-Fulfilling Prophecy

Some critics argue that technical analysis works only because many traders use it, creating a self-fulfilling prophecy. If enough traders identify a support level and place buy orders there, the support level becomes real through their collective action. However, this doesn't mean the pattern has predictive power - it just means traders are responding to the pattern itself.

Criticism 2: Subjectivity

Technical analysis is often subjective - different analysts can interpret the same chart differently. A support level that's obvious to one analyst might be invisible to another. This subjectivity can lead to inconsistent results and makes it difficult to backtest technical strategies objectively.

Criticism 3: Pattern Recognition Bias

Humans are prone to see patterns in random data - a phenomenon called pareidolia. Critics argue that many technical patterns are simply random price movements that traders mistakenly interpret as meaningful patterns. This bias can lead to false signals and poor trading decisions.

Criticism 4: No Theoretical Foundation

Unlike fundamental analysis, which has a clear theoretical foundation (intrinsic value equals present value of future cash flows), technical analysis lacks a solid theoretical basis. Critics argue that without a theoretical foundation, technical analysis is nothing more than reading tea leaves.

Criticism 5: Market Efficiency

The efficient market hypothesis suggests that if technical analysis worked consistently, arbitrageurs would exploit the patterns until they disappeared. The fact that these patterns persist suggests they may not be as reliable as technical analysts claim.

Criticism 6: Look-Ahead Bias

Technical analysis often suffers from look-ahead bias - patterns that seem obvious in hindsight may not have been identifiable in real-time. This can make technical analysis appear more effective in backtesting than it is in actual trading.

Despite these criticisms, technical analysis remains widely used and has many successful practitioners. The key is understanding its limitations, using it as one tool among many, and always combining it with proper risk management.


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

3. Candlestick Patterns

Introduction: Reading Price Action Through Candlesticks

Candlestick patterns are among the most powerful tools in technical analysis, providing immediate visual feedback about market sentiment and potential reversals. Developed in Japan over 300 years ago for analyzing rice futures, candlestick patterns have become fundamental to modern technical analysis because they capture the psychology of market participants in a single visual representation.

The power of candlestick patterns lies in their ability to tell a story about the battle between buyers and sellers during each trading period. Each candlestick shows not just where price closed, but how it got there - the struggle between buyers and sellers, the rejection of certain price levels, and the final outcome of that period's trading. This rich information makes candlestick patterns particularly valuable for identifying potential reversals and continuation points.

Candlestick patterns work because they reflect consistent human psychology. When sellers push prices lower but buyers reject those lower prices (creating a long lower wick), it shows that buyers are stepping in at that level. This psychological pattern - fear of lower prices followed by buying interest - tends to repeat, making candlestick patterns reliable indicators of potential price reversals.

Understanding Candlestick Construction

Before we can identify and trade candlestick patterns, we must understand how candlesticks are constructed and what information they convey. Each element of a candlestick - the body, the wicks, the color - tells part of the story of market behavior during that period.

Body and Shadows

The body of a candlestick represents the range between the opening and closing prices. It's the thick part of the candle and is the most visually prominent element. The body size tells us about the strength of buying or selling pressure - a large body indicates strong directional movement, while a small body suggests indecision and weak directional movement.

The shadows (also called wicks or tails) are the thin lines extending above and below the body. They represent the price range beyond the open-close range - the high and low prices reached during the period. The upper shadow shows how high prices went before being rejected, while the lower shadow shows how low prices went before being rejected.

Long shadows are particularly significant because they show rejection of certain price levels. A long upper shadow indicates that buyers pushed prices higher, but sellers rejected those higher prices and pushed them back down. A long lower shadow indicates that sellers pushed prices lower, but buyers rejected those lower prices and pushed them back up. These rejections often signal support or resistance levels and potential reversal points.

Bullish vs. Bearish Candles

Candlesticks are color-coded to immediately convey whether buyers or sellers controlled the period. In most charting systems, a bullish candle (typically green or white) indicates that the closing price was higher than the opening price, meaning buyers were in control. A bearish candle (typically red or black) indicates that the closing price was lower than the opening price, meaning sellers were in control.

The color coding makes it easy to see at a glance the overall sentiment during each period. A series of green candles suggests strong buying pressure and an uptrend, while a series of red candles suggests strong selling pressure and a downtrend. However, the size and shape of the candles provide additional nuance - a small green candle with a long upper shadow suggests that while buyers closed the period in control, sellers rejected higher prices, which might signal weakening buying pressure.

Opening and Closing Prices

The relationship between the opening and closing prices determines the candle's color and provides insight into the period's trading dynamics. The opening price represents where trading began - the price at which the first trade occurred. The closing price represents where trading ended - the price at which the last trade occurred.

The relationship between these prices tells us about the battle between buyers and sellers. If the close is significantly above the open (a large green body), buyers dominated the period. If the close is significantly below the open (a large red body), sellers dominated. If the open and close are very close (a small body or doji), neither buyers nor sellers gained control, suggesting indecision and potential reversal.

Single Candlestick Patterns

Single candlestick patterns are formed by one candle and provide immediate signals about market sentiment and potential reversals. These patterns are particularly useful because they can be identified quickly and don't require waiting for multiple periods to confirm.

Doji

The doji is one of the most important single-candlestick patterns because it signals indecision and potential reversal. A doji forms when the opening and closing prices are essentially the same, creating a very small body (or no body at all).

Doji: A candlestick pattern where the opening and closing prices are essentially equal, creating a very small or nonexistent body. The doji signals indecision in the market and potential trend reversal, as neither buyers nor sellers gained control during the period.

The doji pattern is significant because it shows that despite price movement during the period (as evidenced by the wicks), buyers and sellers ended the period at essentially the same level. This balance suggests that the prevailing trend may be losing momentum and that a reversal might be imminent. The doji is particularly powerful when it appears after a strong directional move, as it suggests that the trend is exhausted.

There are several variations of the doji, each with slightly different implications. The standard doji has approximately equal upper and lower shadows, suggesting perfect balance. The long-legged doji has very long shadows on both sides, showing high volatility and strong rejection of both higher and lower prices. The gravestone doji has a long upper shadow and no lower shadow, suggesting that buyers pushed prices higher but sellers rejected them completely. The dragonfly doji has a long lower shadow and no upper shadow, suggesting that sellers pushed prices lower but buyers rejected them completely.

Hammer and Hanging Man

The hammer and hanging man are identical candlestick formations that have different meanings depending on their context. Both patterns have a small body at the top of the trading range, a long lower shadow, and little or no upper shadow.

Hammer: A bullish reversal pattern with a small body at the top of the trading range, a long lower shadow (at least twice the body size), and little or no upper shadow. The hammer appears after a downtrend and signals potential reversal to the upside.

The hammer pattern tells a story of rejection. During the period, sellers pushed prices significantly lower (creating the long lower shadow), but buyers stepped in and rejected those lower prices, pushing prices back up to close near the open. This rejection of lower prices, especially after a downtrend, suggests that buyers are gaining strength and that the downtrend may be reversing.

The hanging man is identical in appearance to the hammer but appears after an uptrend and signals potential reversal to the downside. The same price action - sellers pushing prices lower but buyers rejecting them - has different implications in an uptrend. In an uptrend, a hanging man suggests that while buyers still control the close, sellers are becoming more aggressive, which might signal the beginning of a reversal.

The key to distinguishing between a hammer and a hanging man is context. The same candlestick formation is a hammer if it appears after a downtrend (bullish reversal signal) and a hanging man if it appears after an uptrend (bearish reversal signal). This context-dependence is why understanding the prevailing trend is essential for candlestick pattern analysis.

Shooting Star and Inverted Hammer

The shooting star and inverted hammer are the mirror images of the hammer and hanging man. Both patterns have a small body at the bottom of the trading range, a long upper shadow, and little or no lower shadow.

Shooting Star: A bearish reversal pattern with a small body at the bottom of the trading range, a long upper shadow (at least twice the body size), and little or no lower shadow. The shooting star appears after an uptrend and signals potential reversal to the downside.

The shooting star tells a story of rejection at higher prices. During the period, buyers pushed prices significantly higher (creating the long upper shadow), but sellers stepped in and rejected those higher prices, pushing prices back down to close near the open. This rejection of higher prices, especially after an uptrend, suggests that sellers are gaining strength and that the uptrend may be reversing.

The inverted hammer is identical in appearance to the shooting star but appears after a downtrend and signals potential reversal to the upside. The same price action - buyers pushing prices higher but sellers rejecting them - has different implications in a downtrend. In a downtrend, an inverted hammer suggests that while sellers still control the close, buyers are becoming more aggressive, which might signal the beginning of a reversal.

Marubozu

The marubozu is a candlestick with no shadows - the body extends from the high to the low of the period. This pattern indicates strong directional movement with no rejection of prices at either extreme.

Marubozu: A candlestick pattern with no shadows, where the body extends from the high to the low of the trading period. A bullish marubozu (green) indicates strong buying pressure with no rejection of higher prices, while a bearish marubozu (red) indicates strong selling pressure with no rejection of lower prices.

The marubozu pattern is significant because it shows that one side (buyers or sellers) completely dominated the period without any rejection. A bullish marubozu shows that buyers were in complete control - prices opened at the low and closed at the high, with no rejection of higher prices. This suggests very strong buying pressure. A bearish marubozu shows the opposite - sellers were in complete control, with prices opening at the high and closing at the low.

Marubozu candles are particularly powerful when they appear in a series or at key support/resistance levels. A series of bullish marubozu candles suggests extremely strong buying pressure and a strong uptrend. A bullish marubozu at a support level suggests that buyers are strongly defending that level. However, marubozu candles can also signal exhaustion - after a series of marubozu candles, the trend may be due for a reversal.

Two-Candlestick Patterns

Two-candlestick patterns combine the information from two consecutive periods to provide stronger signals than single-candlestick patterns. These patterns show how the battle between buyers and sellers evolves over two periods, providing more reliable reversal and continuation signals.

Engulfing Patterns (Bullish and Bearish)

Engulfing patterns are among the most reliable two-candlestick reversal patterns. They occur when the body of the second candle completely engulfs (covers) the body of the first candle, signaling a strong shift in market sentiment.

Bullish Engulfing Pattern: A two-candlestick bullish reversal pattern where a bearish candle is followed by a larger bullish candle whose body completely engulfs the body of the first candle. The pattern signals that buyers have taken control and that a reversal to the upside is likely.

The bullish engulfing pattern tells a clear story of sentiment shift. The first candle (bearish) shows that sellers were in control - prices closed lower than they opened. However, the second candle (bullish) shows that buyers completely overwhelmed sellers - not only did prices recover from the first candle's decline, but they closed higher than the first candle opened. This complete reversal of the first candle's body shows that buying pressure has completely overwhelmed selling pressure.

The bearish engulfing pattern is the opposite - a bullish candle is followed by a larger bearish candle whose body completely engulfs the first candle's body. This signals that sellers have taken control and that a reversal to the downside is likely.

Engulfing patterns are particularly reliable when: (1) they occur after a strong trend (showing exhaustion), (2) the second candle's body is significantly larger than the first (showing strong reversal pressure), (3) volume is higher on the second candle (confirming the reversal), and (4) the pattern occurs at key support or resistance levels.

Python exercise

#| label: fig-engulfing-patterns
#| fig-cap: "Engulfing Patterns: Enhanced Analysis - Volume Confirmation, Pattern Strength, and Trading Signals"
#| 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 IPython.display import display
from datetime import datetime, timedelta

# 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('Engulfing Patterns: Enhanced Analysis - Volume Confirmation, Pattern Strength, and Trading Signals', 
             fontsize=17, fontweight='bold', y=0.98)

# Generate bullish engulfing pattern data with volume
np.random.seed(42)
dates_bull = [datetime(2024, 1, 1) + timedelta(days=i) for i in range(10)]
base_volume = 1000000

# Create downtrend leading to bullish engulfing
ohlc_bull = []
volumes_bull = []
for i in range(8):
    open_price = 100 - i * 1.5
    close_price = open_price - 1 - np.random.normal(0, 0.3)
    high_price = open_price + 0.5
    low_price = close_price - 1
    ohlc_bull.append((open_price, high_price, low_price, close_price))
    volumes_bull.append(base_volume * (0.9 + i * 0.05) + np.random.normal(0, 70000))

# Bullish engulfing pattern
# First candle (bearish) - lower volume
open1 = 88
close1 = 86
high1 = 88.5
low1 = 85
body1 = abs(close1 - open1)
ohlc_bull.append((open1, high1, low1, close1))
volumes_bull.append(base_volume * 0.8 + np.random.normal(0, 60000))

# Second candle (bullish, engulfs first) - high volume
open2 = 85.5
close2 = 90  # Engulfs first candle's open
high2 = 90.5
low2 = 85
body2 = abs(close2 - open2)
ohlc_bull.append((open2, high2, low2, close2))
volumes_bull.append(base_volume * 2.5 + np.random.normal(0, 150000))  # High volume confirmation

# Calculate pattern metrics
engulfing_ratio = body2 / body1
volume_ratio = volumes_bull[-1] / volumes_bull[-2]

# Panel 1: Bullish Engulfing Pattern
ax1 = fig.add_subplot(gs[0, 0])
for i, (date, (open_price, high, low, close_price)) in enumerate(zip(dates_bull, ohlc_bull)):
    wick_color = 'black'
    ax1.plot([date, date], [low, high], color=wick_color, linewidth=1.5, alpha=0.7)
    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.5, alpha=0.9)
    ax1.add_patch(rect)

# Highlight engulfing pattern
ax1.annotate('Bearish Candle\n(Sellers)', 
            xy=(dates_bull[-2], ohlc_bull[-2][3]), xytext=(-25, 30),
            textcoords='offset points', fontsize=9, fontweight='bold',
            bbox=dict(boxstyle='round', facecolor='red', alpha=0.8),
            arrowprops=dict(arrowstyle='->', color='black', lw=1.5))
ax1.annotate(f'Bullish Engulfing\n({engulfing_ratio:.1f}x size)', 
            xy=(dates_bull[-1], ohlc_bull[-1][3]), xytext=(25, 30),
            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: Bullish Engulfing Pattern (Bearish to Bullish Reversal)', 
              fontsize=13, fontweight='bold')
ax1.set_ylabel('Price ($)', fontsize=11, fontweight='bold')
ax1.grid(True, alpha=0.3, linestyle='--')
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d'))

# Panel 2: Bearish Engulfing Pattern
dates_bear = [datetime(2024, 1, 1) + timedelta(days=i) for i in range(10)]
ohlc_bear = []
volumes_bear = []

# Create uptrend leading to bearish engulfing
for i in range(8):
    open_price = 90 + i * 1.5
    close_price = open_price + 1 + np.random.normal(0, 0.3)
    high_price = close_price + 0.5
    low_price = open_price - 1
    ohlc_bear.append((open_price, high_price, low_price, close_price))
    volumes_bear.append(base_volume * (0.9 + i * 0.05) + np.random.normal(0, 70000))

# Bearish engulfing pattern
open1 = 102
close1 = 104
high1 = 104.5
low1 = 101.5
body1_bear = abs(close1 - open1)
ohlc_bear.append((open1, high1, low1, close1))
volumes_bear.append(base_volume * 0.8 + np.random.normal(0, 60000))

open2 = 103.5
close2 = 99
high2 = 103.5
low2 = 98.5
body2_bear = abs(close2 - open2)
ohlc_bear.append((open2, high2, low2, close2))
volumes_bear.append(base_volume * 2.5 + np.random.normal(0, 150000))

engulfing_ratio_bear = body2_bear / body1_bear
volume_ratio_bear = volumes_bear[-1] / volumes_bear[-2]

ax2 = fig.add_subplot(gs[0, 1])
for i, (date, (open_price, high, low, close_price)) in enumerate(zip(dates_bear, ohlc_bear)):
    ax2.plot([date, date], [low, high], color='black', linewidth=1.5, alpha=0.7)
    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.5, alpha=0.9)
    ax2.add_patch(rect)

ax2.annotate('Bullish Candle\n(Buyers)', 
            xy=(dates_bear[-2], ohlc_bear[-2][3]), xytext=(-25, -35),
            textcoords='offset points', fontsize=9, fontweight='bold',
            bbox=dict(boxstyle='round', facecolor='green', alpha=0.8),
            arrowprops=dict(arrowstyle='->', color='black', lw=1.5))
ax2.annotate(f'Bearish Engulfing\n({engulfing_ratio_bear:.1f}x size)', 
            xy=(dates_bear[-1], ohlc_bear[-1][3]), xytext=(25, -35),
            textcoords='offset points', fontsize=10, fontweight='bold',
            bbox=dict(boxstyle='round', facecolor='red', alpha=0.8),
            arrowprops=dict(arrowstyle='->', color='red', lw=2.5))

ax2.set_title('Panel 2: Bearish Engulfing Pattern (Bullish to Bearish Reversal)', 
              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: Volume Analysis
ax3 = fig.add_subplot(gs[1, 0])
pattern_types = ['Bullish\nEngulfing', 'Bearish\nEngulfing']
volume_ratios_plot = [volume_ratio, volume_ratio_bear]
body_ratios_plot = [engulfing_ratio, engulfing_ratio_bear]

x = np.arange(len(pattern_types))
width = 0.35

bars1 = ax3.bar(x - width/2, volume_ratios_plot, width, label='Volume Ratio', 
                color=['green', 'red'], alpha=0.7, edgecolor='black', linewidth=1.5)
bars2 = ax3.bar(x + width/2, body_ratios_plot, width, label='Body Size Ratio', 
                color=['lightgreen', 'lightcoral'], alpha=0.7, edgecolor='black', linewidth=1.5)

for bar, val in zip(bars1, volume_ratios_plot):
    height = bar.get_height()
    ax3.text(bar.get_x() + bar.get_width()/2., height + 0.1,
            f'{val:.2f}x', ha='center', va='bottom', fontsize=9, fontweight='bold')
for bar, val in zip(bars2, body_ratios_plot):
    height = bar.get_height()
    ax3.text(bar.get_x() + bar.get_width()/2., height + 0.1,
            f'{val:.2f}x', ha='center', va='bottom', fontsize=9, fontweight='bold')

ax3.set_title('Panel 3: Pattern Strength Metrics - Volume & Body Size Ratios', 
              fontsize=12, fontweight='bold')
ax3.set_ylabel('Ratio', fontsize=11, fontweight='bold')
ax3.set_xticks(x)
ax3.set_xticklabels(pattern_types, fontsize=10)
ax3.legend(loc='upper left', fontsize=9)
ax3.grid(True, alpha=0.3, linestyle='--', axis='y')

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

formula_text = f"""
Engulfing Pattern Analysis:

Pattern Requirements:
• Candle 1: Small body in trend direction
• Candle 2: Large body opposite direction
• Candle 2 body completely engulfs Candle 1 body
• Higher volume on Candle 2 (confirmation)

Pattern Metrics:
• Bullish Engulfing:
  - Body Ratio: {engulfing_ratio:.2f}x
  - Volume Ratio: {volume_ratio:.2f}x
  - Reliability: {'High' if volume_ratio > 2.0 and engulfing_ratio > 1.5 else 'Medium'}

• Bearish Engulfing:
  - Body Ratio: {engulfing_ratio_bear:.2f}x
  - Volume Ratio: {volume_ratio_bear:.2f}x
  - Reliability: {'High' if volume_ratio_bear > 2.0 and engulfing_ratio_bear > 1.5 else 'Medium'}

Trading Signals:
• Entry: On pattern completion (Candle 2 close)
• Stop Loss: Beyond opposite side of pattern
• Target: Pattern height projected
• Confirmation: High volume (2x+ average)

Pattern Strength Factors:
✓ Larger engulfing candle = stronger signal
✓ Higher volume = more reliable
✓ At support/resistance = stronger
✓ After strong trend = more reliable
✓ Multiple confirmations = stronger
"""

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)

Harami Patterns

Harami patterns (from the Japanese word for "pregnant") are the opposite of engulfing patterns. They occur when a large candle is followed by a small candle whose body is completely contained within the body of the first candle.

Bullish Harami Pattern: A two-candlestick bullish reversal pattern where a large bearish candle is followed by a small candle (bullish or bearish) whose body is completely contained within the first candle's body. The pattern signals that selling pressure is weakening and that a reversal to the upside may be imminent.

The harami pattern shows a different type of sentiment shift than the engulfing pattern. While the engulfing pattern shows an immediate, strong reversal, the harami pattern shows a more gradual shift - the large first candle shows strong directional pressure, but the small second candle shows that this pressure is weakening. The small second candle, contained within the first, suggests that the market is pausing and that the prevailing trend may be losing momentum.

The bearish harami pattern is the opposite - a large bullish candle is followed by a small candle contained within it, signaling that buying pressure is weakening and that a reversal to the downside may be imminent.

Piercing Pattern and Dark Cloud Cover

The piercing pattern and dark cloud cover are two-candlestick patterns that show partial engulfing - the second candle doesn't completely engulf the first, but it shows a significant shift in sentiment.

Piercing Pattern: A bullish reversal pattern consisting of a bearish candle followed by a bullish candle that opens below the first candle's low but closes above the midpoint of the first candle's body. The pattern signals that buyers are recovering from selling pressure and that a reversal to the upside is likely.

The piercing pattern shows buyers recovering from selling pressure. The first candle (bearish) shows strong selling pressure. The second candle (bullish) opens even lower, suggesting continued selling, but then buyers step in and push prices up, closing above the midpoint of the first candle. This recovery shows that buyers are gaining strength and that the downtrend may be reversing.

Dark Cloud Cover is the bearish counterpart - a bullish candle is followed by a bearish candle that opens above the first candle's high but closes below the midpoint of the first candle's body. This shows that sellers are recovering from buying pressure and that the uptrend may be reversing.

Tweezers

Tweezer patterns occur when two consecutive candles have the same high (tweezer tops) or the same low (tweezer bottoms). These patterns signal rejection at specific price levels and potential reversal.

Tweezer Tops: A bearish reversal pattern consisting of two consecutive candles with the same high price. The pattern signals that buyers attempted to push prices higher but were rejected at the same level twice, suggesting that resistance is strong and that a reversal to the downside is likely.

Tweezer patterns are simple but effective - they show that the market tested a specific price level twice and was rejected both times. This double rejection suggests that the level is significant and that a reversal is likely. Tweezer tops are particularly powerful when they occur at resistance levels, and tweezer bottoms are powerful when they occur at support levels.

Three-Candlestick Patterns

Three-candlestick patterns provide even stronger signals than two-candlestick patterns because they show how sentiment evolves over three periods. These patterns are generally more reliable but take longer to form, making them better suited for longer-term trading decisions.

Morning Star and Evening Star

The morning star and evening star are among the most reliable three-candlestick reversal patterns. They consist of three candles that together tell a complete story of trend reversal.

Morning Star Pattern: A bullish reversal pattern consisting of three candles: (1) a large bearish candle showing strong selling pressure, (2) a small candle (often a doji or spinning top) that gaps down from the first candle, showing indecision, and (3) a large bullish candle that gaps up and closes well into the first candle's body, confirming the reversal.

The morning star pattern tells a complete reversal story. The first candle shows strong selling pressure in a downtrend. The second candle shows indecision - it gaps down (continuing the downtrend) but is small, suggesting that selling pressure is weakening. The third candle confirms the reversal by gapping up and closing well into the first candle's body, showing that buyers have taken control.

The evening star pattern is the bearish counterpart - a large bullish candle is followed by a small indecision candle that gaps up, which is then followed by a large bearish candle that gaps down and closes well into the first candle's body.

Python exercise

#| label: fig-morning-evening-star
#| fig-cap: "Morning Star and Evening Star Patterns: Enhanced Analysis - Volume Confirmation, Pattern Phases, and Trading Signals"
#| 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 IPython.display import display
from datetime import datetime, timedelta

# 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('Morning Star and Evening Star Patterns: Enhanced Analysis - Volume Confirmation, Pattern Phases, and Trading Signals', 
             fontsize=17, fontweight='bold', y=0.98)

# Generate morning star pattern data with volume
np.random.seed(42)
dates_morning = [datetime(2024, 1, 1) + timedelta(days=i) for i in range(10)]
base_volume = 1000000

# Create downtrend leading to morning star
ohlc_morning = []
volumes_morning = []
for i in range(7):
    open_price = 100 - i * 2
    close_price = open_price - 1.5 - np.random.normal(0, 0.3)
    high_price = open_price + 0.5
    low_price = close_price - 1
    ohlc_morning.append((open_price, high_price, low_price, close_price))
    volumes_morning.append(base_volume * (1.0 + i * 0.1) + np.random.normal(0, 80000))

# Morning star pattern
# First candle (large bearish) - high volume
open1 = 86
close1 = 83
high1 = 86.5
low1 = 82
body1 = abs(close1 - open1)
ohlc_morning.append((open1, high1, low1, close1))
volumes_morning.append(base_volume * 1.5 + np.random.normal(0, 100000))

# Second candle (small, gaps down, doji-like) - low volume
open2 = 82.5  # Gap down
close2 = 82.7  # Small body (doji)
high2 = 83.5
low2 = 82.2
body2 = abs(close2 - open2)
ohlc_morning.append((open2, high2, low2, close2))
volumes_morning.append(base_volume * 0.6 + np.random.normal(0, 50000))  # Low volume indecision

# Third candle (large bullish, gaps up) - high volume
open3 = 84  # Gap up
close3 = 87  # Closes well into first candle's body
high3 = 87.5
low3 = 83.5
body3 = abs(close3 - open3)
ohlc_morning.append((open3, high3, low3, close3))
volumes_morning.append(base_volume * 2.2 + np.random.normal(0, 120000))  # High volume confirmation

# Calculate pattern metrics
gap1 = open2 - close1  # Gap down
gap2 = open3 - close2  # Gap up
penetration = (close3 - open1) / body1  # How much third candle penetrates first
volume_ratio_morning = volumes_morning[-1] / volumes_morning[-2]

# Panel 1: Morning Star Pattern
ax1 = fig.add_subplot(gs[0, 0])
for i, (date, (open_price, high, low, close_price)) in enumerate(zip(dates_morning, ohlc_morning)):
    ax1.plot([date, date], [low, high], color='black', linewidth=1.5, alpha=0.7)
    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.5, alpha=0.9)
    ax1.add_patch(rect)

# Annotate pattern phases
ax1.annotate('Phase 1: Large Bearish\n(Strong Selling)', 
            xy=(dates_morning[-3], ohlc_morning[-3][3]), xytext=(-25, -35),
            textcoords='offset points', fontsize=9, fontweight='bold',
            bbox=dict(boxstyle='round', facecolor='red', alpha=0.8),
            arrowprops=dict(arrowstyle='->', color='black', lw=1.5))
ax1.annotate('Phase 2: Small Doji\n(Indecision, Gap Down)', 
            xy=(dates_morning[-2], ohlc_morning[-2][3]), xytext=(25, 20),
            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('Phase 3: Large Bullish\n(Reversal, Gap Up)', 
            xy=(dates_morning[-1], ohlc_morning[-1][3]), xytext=(25, 30),
            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: Morning Star Pattern (Bullish Reversal)', fontsize=13, fontweight='bold')
ax1.set_ylabel('Price ($)', fontsize=11, fontweight='bold')
ax1.grid(True, alpha=0.3, linestyle='--')
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d'))

# Generate evening star pattern data with volume
dates_evening = [datetime(2024, 1, 1) + timedelta(days=i) for i in range(10)]
ohlc_evening = []
volumes_evening = []

# Create uptrend leading to evening star
for i in range(7):
    open_price = 90 + i * 2
    close_price = open_price + 1.5 + np.random.normal(0, 0.3)
    high_price = close_price + 0.5
    low_price = open_price - 1
    ohlc_evening.append((open_price, high_price, low_price, close_price))
    volumes_evening.append(base_volume * (1.0 + i * 0.1) + np.random.normal(0, 80000))

# Evening star pattern
open1 = 104
close1 = 107
high1 = 107.5
low1 = 103.5
body1_evening = abs(close1 - open1)
ohlc_evening.append((open1, high1, low1, close1))
volumes_evening.append(base_volume * 1.5 + np.random.normal(0, 100000))

open2 = 107.5  # Gap up
close2 = 107.3  # Small body (doji)
high2 = 108
low2 = 106.8
body2_evening = abs(close2 - open2)
ohlc_evening.append((open2, high2, low2, close2))
volumes_evening.append(base_volume * 0.6 + np.random.normal(0, 50000))

open3 = 106  # Gap down
close3 = 103  # Closes well into first candle's body
high3 = 106.5
low3 = 102.5
body3_evening = abs(close3 - open3)
ohlc_evening.append((open3, high3, low3, close3))
volumes_evening.append(base_volume * 2.2 + np.random.normal(0, 120000))

gap1_evening = open2 - close1
gap2_evening = open3 - close2
penetration_evening = (open1 - close3) / body1_evening
volume_ratio_evening = volumes_evening[-1] / volumes_evening[-2]

# Panel 2: Evening Star Pattern
ax2 = fig.add_subplot(gs[0, 1])
for i, (date, (open_price, high, low, close_price)) in enumerate(zip(dates_evening, ohlc_evening)):
    ax2.plot([date, date], [low, high], color='black', linewidth=1.5, alpha=0.7)
    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.5, alpha=0.9)
    ax2.add_patch(rect)

ax2.annotate('Phase 1: Large Bullish\n(Strong Buying)', 
            xy=(dates_evening[-3], ohlc_evening[-3][3]), xytext=(-25, 35),
            textcoords='offset points', fontsize=9, fontweight='bold',
            bbox=dict(boxstyle='round', facecolor='green', alpha=0.8),
            arrowprops=dict(arrowstyle='->', color='black', lw=1.5))
ax2.annotate('Phase 2: Small Doji\n(Indecision, Gap Up)', 
            xy=(dates_evening[-2], ohlc_evening[-2][3]), xytext=(25, -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))
ax2.annotate('Phase 3: Large Bearish\n(Reversal, Gap Down)', 
            xy=(dates_evening[-1], ohlc_evening[-1][3]), xytext=(25, -35),
            textcoords='offset points', fontsize=10, fontweight='bold',
            bbox=dict(boxstyle='round', facecolor='red', alpha=0.8),
            arrowprops=dict(arrowstyle='->', color='red', lw=2.5))

ax2.set_title('Panel 2: Evening Star Pattern (Bearish Reversal)', 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: Volume Analysis
ax3 = fig.add_subplot(gs[1, 0])
pattern_phases = ['Phase 1\n(Large)', 'Phase 2\n(Doji)', 'Phase 3\n(Reversal)']
volumes_morning_norm = [v / max(volumes_morning) * 100 for v in volumes_morning[-3:]]
volumes_evening_norm = [v / max(volumes_evening) * 100 for v in volumes_evening[-3:]]

x = np.arange(len(pattern_phases))
width = 0.35

bars1 = ax3.bar(x - width/2, volumes_morning_norm, width, label='Morning Star', 
                color='green', alpha=0.7, edgecolor='black', linewidth=1.5)
bars2 = ax3.bar(x + width/2, volumes_evening_norm, width, label='Evening Star', 
                color='red', alpha=0.7, edgecolor='black', linewidth=1.5)

for bar, val in zip(bars1, volumes_morning_norm):
    height = bar.get_height()
    ax3.text(bar.get_x() + bar.get_width()/2., height + 2,
            f'{val:.0f}%', ha='center', va='bottom', fontsize=8, fontweight='bold')
for bar, val in zip(bars2, volumes_evening_norm):
    height = bar.get_height()
    ax3.text(bar.get_x() + bar.get_width()/2., height + 2,
            f'{val:.0f}%', ha='center', va='bottom', fontsize=8, fontweight='bold')

ax3.set_title('Panel 3: Volume Pattern - High Volume on Phase 1 & 3, Low on Phase 2', 
              fontsize=12, fontweight='bold')
ax3.set_ylabel('Normalized Volume (%)', fontsize=11, fontweight='bold')
ax3.set_xticks(x)
ax3.set_xticklabels(pattern_phases, fontsize=10)
ax3.legend(loc='upper left', fontsize=9)
ax3.grid(True, alpha=0.3, linestyle='--', axis='y')

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

formula_text = f"""
Morning/Evening Star Pattern Analysis:

Pattern Structure:
• Phase 1: Large candle in trend direction
• Phase 2: Small doji (gaps from Phase 1)
• Phase 3: Large candle opposite direction (gaps from Phase 2)

Morning Star Metrics:
• Gap 1 (Down): ${abs(gap1):.2f}
• Gap 2 (Up): ${gap2:.2f}
• Penetration: {penetration*100:.1f}% into Phase 1 body
• Volume Ratio: {volume_ratio_morning:.2f}x (Phase 3 vs Phase 2)
• Reliability: {'High' if volume_ratio_morning > 2.0 and penetration > 0.5 else 'Medium'}

Evening Star Metrics:
• Gap 1 (Up): ${gap1_evening:.2f}
• Gap 2 (Down): ${abs(gap2_evening):.2f}
• Penetration: {penetration_evening*100:.1f}% into Phase 1 body
• Volume Ratio: {volume_ratio_evening:.2f}x (Phase 3 vs Phase 2)
• Reliability: {'High' if volume_ratio_evening > 2.0 and penetration_evening > 0.5 else 'Medium'}

Trading Signals:
• Entry: On Phase 3 completion (close)
• Stop Loss: Below Phase 2 low (Morning) / Above Phase 2 high (Evening)
• Target: Pattern height projected
• Confirmation: High volume on Phase 3

Pattern Strength Factors:
✓ Larger Phase 1 & 3 = stronger signal
✓ Clear gaps between phases = stronger
✓ Higher volume on Phase 3 = more reliable
✓ Phase 3 penetrates >50% into Phase 1 = stronger
✓ At support/resistance = more reliable
"""

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)

Three White Soldiers and Three Black Crows

The three white soldiers and three black crows are continuation patterns that show strong directional momentum over three consecutive periods.

Three White Soldiers: A bullish continuation pattern consisting of three consecutive bullish candles, each closing higher than the previous, with each candle opening within or near the previous candle's body. The pattern signals strong buying pressure and continuation of an uptrend.

The three white soldiers pattern shows strong, consistent buying pressure. Each candle closes higher than the previous, showing that buyers are in control and that the trend is strong. The pattern is particularly powerful when each candle opens within the previous candle's body (showing no gaps or rejection), when the candles have small or no shadows (showing no rejection of prices), and when volume increases on each candle (confirming buying interest).

Three Black Crows is the bearish counterpart - three consecutive bearish candles, each closing lower than the previous, signaling strong selling pressure and continuation of a downtrend.

Candlestick Pattern Reliability

Not all candlestick patterns are equally reliable. Understanding the factors that affect pattern reliability helps you focus on the most trustworthy signals and avoid false patterns.

Context is Critical: The same candlestick formation can have different meanings depending on the context. A hammer after a downtrend is a bullish reversal signal, but the same formation after an uptrend (a hanging man) is a bearish reversal signal. Understanding the prevailing trend and market context is essential for accurate pattern interpretation.

Volume Confirmation: Candlestick patterns are more reliable when confirmed by volume. A bullish engulfing pattern with high volume on the second candle is more reliable than one with low volume. Volume confirms that the pattern represents genuine market participation rather than random price movement.

Pattern Location: Patterns at key support or resistance levels are more reliable than patterns in the middle of a range. A hammer at a support level is more likely to signal a reversal than a hammer in the middle of a downtrend where support might not exist.

Multiple Pattern Confirmation: When multiple candlestick patterns confirm each other, reliability increases. For example, a doji followed by a bullish engulfing pattern provides stronger confirmation than either pattern alone.

Timeframe Considerations: Candlestick patterns on longer timeframes (daily, weekly) are generally more reliable than those on shorter timeframes (minutes, hours). However, patterns on shorter timeframes can provide valuable entry and exit points when confirmed by longer-term patterns.

Knowledge Check 8.2

A candlestick pattern appears after a strong downtrend. It has a small body at the top of the trading range, a long lower shadow (at least twice the body size), and little or no upper shadow. What pattern is this, and what does it signal?

A. Shooting star - bearish reversal
B. Hammer - bullish reversal
C. Hanging man - bearish reversal
D. Inverted hammer - bullish continuation

Click to reveal answer

B. Hammer - bullish reversal

The description matches a hammer pattern: small body at the top, long lower shadow, little or no upper shadow. When this pattern appears after a downtrend (the context), it's a hammer and signals a potential bullish reversal. If the same pattern appeared after an uptrend, it would be a hanging man (bearish reversal).

Practice Problem 8.2: Candlestick Pattern Analysis

A stock in a downtrend forms the following three-candlestick pattern:

  • First candle: Large bearish candle (opens $100, closes $95)
  • Second candle: Small candle with body at $94.50 (gaps down from first, opens $94, closes $94.50)
  • Third candle: Large bullish candle (opens $95, closes $98, gaps up from second)
  1. What pattern is this?
  2. What does it signal?
  3. What volume pattern would confirm this pattern?
  4. At what price level would you place a stop loss?
Click to reveal solution

Solution:

1. Pattern Identification:
This is a Morning Star pattern - a three-candlestick bullish reversal pattern.

2. Signal:
The pattern signals a potential reversal from bearish to bullish. The large bearish first candle shows strong selling pressure, the small second candle shows indecision and weakening selling pressure, and the large bullish third candle confirms that buyers have taken control.

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

  • High volume on the first candle (strong selling pressure)
  • Lower volume on the second candle (indecision, weakening pressure)
  • High volume on the third candle (strong buying pressure confirming reversal)

4. Stop Loss Placement:
The stop loss should be placed below the low of the second candle (the small indecision candle), which would be around $94. This protects against the pattern failing if price breaks below the indecision level.


4. Technical Indicators

Module Summary

Throughout this module, we have explored the comprehensive discipline of technical analysis for equities, a field that has evolved from simple price charting to a sophisticated system of pattern recognition, indicator analysis, and market psychology. Technical analysis represents a fundamentally different approach to market evaluation compared to fundamental analysis, focusing not on what a company is worth, but on how the market is behaving and what that behavior might predict about future price movements.

The journey through this module has taken us from the foundational principles that underpin technical analysis to the practical application of complex trading strategies. We began with understanding the philosophical assumptions that make technical analysis possible - that markets discount everything, that prices move in trends, and that history tends to repeat itself because human psychology remains constant. These principles, while not universally accepted, provide the theoretical foundation upon which all technical analysis techniques are built.

Key Concepts Covered

Our exploration began with chart patterns, the visual language of technical analysis. These patterns emerge from the collective psychology of market participants, creating recognizable formations that reflect shifts in supply and demand. We examined reversal patterns like head and shoulders, double tops, and triple tops - patterns that signal the exhaustion of existing trends and the potential for directional change. We also explored continuation patterns like flags, pennants, and triangles - formations that represent temporary pauses in trends before resumption of the original direction. These patterns are not mere geometric shapes on a chart; they represent the ebb and flow of trader sentiment, the battle between buyers and sellers, and the psychological dynamics that drive market movements.

From chart patterns, we moved to candlestick analysis, a more granular view of price action that reveals the intraday psychology of market participants. Each candlestick tells a story - the balance between buying and selling pressure, the confidence of traders, and the potential for reversal or continuation. Single candlestick patterns like doji, hammers, and shooting stars provide immediate signals about market sentiment. Two-candlestick patterns like engulfing patterns and harami formations reveal shifts in momentum. Three-candlestick patterns like morning stars and evening stars provide confirmation of trend changes. Understanding candlestick patterns is like learning to read the body language of the market - subtle signals that can precede major price movements.

The module then delved deeply into technical indicators, the mathematical tools that transform raw price and volume data into actionable insights. We explored the comprehensive landscape of technical indicators, organized into functional categories. Trend-following indicators - including moving averages (SMA, EMA, WMA, DEMA, TEMA), MACD, ADX, Parabolic SAR, and Ichimoku Cloud - help identify the direction and strength of trends. These indicators smooth out price noise and reveal underlying trend dynamics. Momentum indicators - including RSI, Stochastic Oscillator, Williams %R, CCI, and many others - measure the rate of price change and help identify overbought and oversold conditions. Volume indicators - such as OBV, A/D Line, Chaikin Money Flow, and VWAP - provide crucial confirmation of price movements and reveal accumulation and distribution patterns. Volatility indicators - including Bollinger Bands, ATR, and Keltner Channels - help assess market risk and identify potential breakout conditions. Each category of indicators serves distinct analytical purposes, and their effective combination requires understanding both their individual characteristics and their relationships.

We explored support and resistance analysis, fundamental concepts that define the boundaries within which prices move. Support levels represent areas where buying pressure has historically been strong enough to halt or reverse declines. Resistance levels represent areas where selling pressure has historically been strong enough to halt or reverse advances. These levels are not fixed lines but dynamic zones that reflect the collective memory of market participants. Pivot points and Fibonacci retracements provide mathematical frameworks for identifying potential support and resistance levels, while psychological levels and volume profile analysis reveal areas of high trading activity that often serve as support or resistance.

Trend analysis formed a central pillar of the module, recognizing that understanding trends is essential for successful trading. We examined how to identify trends - through price action, moving averages, and trendlines. We explored how to assess trend strength - through duration, steepness, and consistency. We learned to recognize trend reversals through multiple signals including price action breaks, indicator divergences, volume patterns, and reversal chart formations. Perhaps most importantly, we developed comprehensive strategies for trading with trends - trend continuation strategies that ride existing trends, and pullback trading strategies that enter trends at optimal prices. The psychology of trend trading emerged as a critical component, recognizing that successful trend following requires discipline, patience, and the ability to let winners run while cutting losses short.

Volume analysis completed our analytical toolkit, providing the crucial context that transforms price movements into meaningful signals. Volume is the fuel of price movements - without volume, price movements lack conviction and may be short-lived. We learned that volume should confirm price movements, that volume divergences often precede reversals, and that volume spikes can signal important market events. Volume analysis helps distinguish between genuine breakouts and false signals, identifies accumulation and distribution, and provides confirmation for signals from other technical tools. Volume-weighted average price (VWAP) emerged as a critical benchmark for institutional trading, while volume profile analysis reveals where the most trading activity has occurred, identifying key support and resistance levels.

Connections to Other Modules

The concepts and techniques explored in this module connect deeply with other modules in the PriceWhisperer curriculum, creating a comprehensive understanding of equity markets. The mathematical foundations from Module 4 (Mathematics) underpin all technical indicators - moving averages, statistical measures, and probability concepts are essential for understanding how indicators work and how to interpret their signals. The fundamental analysis concepts from Module 5 (Stock Fundamentals) and Module 6 (Equity Valuation) provide context for technical analysis - understanding a company's fundamentals helps identify when technical patterns are more or less significant. The market microstructure concepts from Module 7 (Equity Trading) explain how orders flow into the market and how that flow creates the patterns and signals that technical analysts observe.

The relationship between technical and fundamental analysis is particularly important. While this module focuses on technical analysis, successful traders and investors often combine both approaches. Fundamental analysis can help identify which stocks are worth analyzing technically - a fundamentally strong company in an uptrend is more attractive than a fundamentally weak company in an uptrend. Technical analysis can help time entries into fundamentally attractive stocks - buying a fundamentally sound company at a technically optimal entry point improves risk/reward ratios. The integration of these approaches creates a more robust investment process than either approach alone.

Critical Technical Analysis Concepts

Several concepts emerged as particularly critical for understanding and applying technical analysis effectively. The first is confirmation - the principle that single signals are often unreliable and that multiple confirmations from different sources increase the probability of successful trades. A breakout confirmed by volume, validated by indicators, and supported by trend analysis is far more reliable than a breakout that appears in isolation. This principle of confirmation runs throughout technical analysis and is essential for avoiding false signals.

The second critical concept is context - understanding that technical patterns and signals must be interpreted within their market context. A head and shoulders pattern that forms after a strong uptrend is more significant than one that forms during a sideways market. An RSI overbought reading in a strong uptrend may not be a reversal signal but rather a sign of trend strength. Understanding context requires analyzing multiple timeframes, considering market conditions, and recognizing that the same pattern can have different meanings in different situations.

The third critical concept is risk management - recognizing that technical analysis is a tool for managing risk, not eliminating it. No technical pattern or indicator is infallible, and all can produce false signals. Proper risk management through stop-losses, position sizing, and exit strategies is essential for long-term success. Technical analysis helps identify entry and exit points and assess risk/reward ratios, but it cannot guarantee profits or prevent losses. The discipline to follow technical signals even when they conflict with emotions, and to exit positions when technical analysis suggests reversal, is crucial for success.

The fourth critical concept is integration - understanding that the most powerful technical analysis combines multiple tools and techniques rather than relying on a single approach. A trader who uses only moving averages misses the insights from volume analysis. A trader who focuses only on chart patterns misses the confirmation from technical indicators. The most effective technical analysis integrates price action, chart patterns, technical indicators, volume analysis, and trend analysis into a cohesive system that provides multiple perspectives on market conditions.

Professional Applications

The techniques and concepts explored in this module have numerous professional applications across the trading and investment industry. Professional traders use technical analysis to identify entry and exit points, manage risk, and time trades. Portfolio managers use technical analysis to time entries and exits for positions, to assess market conditions, and to manage risk. Quantitative analysts incorporate technical indicators into algorithmic trading systems, creating systematic strategies that execute trades based on technical signals.

In the context of PriceWhisperer, technical analysis provides the foundation for automated trading systems that can identify opportunities, assess risk, and execute trades. The comprehensive coverage of technical indicators, chart patterns, and trading strategies enables the development of sophisticated trading algorithms that can analyze multiple dimensions of market behavior simultaneously. The integration of technical analysis with fundamental analysis and risk management creates a holistic approach to equity trading that can adapt to different market conditions.

For individual traders and investors, the concepts in this module provide practical tools for making trading decisions. The ability to identify trends, recognize chart patterns, interpret technical indicators, analyze volume, and understand support and resistance levels creates a comprehensive framework for market analysis. However, it's important to recognize that technical analysis is a skill that requires practice, discipline, and continuous learning. The markets are dynamic, and successful technical analysis requires adapting to changing market conditions and continuously refining one's approach.

The module has also emphasized the importance of understanding the limitations and criticisms of technical analysis. No analytical approach is perfect, and technical analysis has its critics and limitations. Understanding these limitations - including subjectivity, the potential for self-fulfilling prophecies, and the lack of theoretical foundation - helps traders use technical analysis more effectively and avoid common pitfalls. The goal is not to find a perfect system but to develop a robust approach that provides a statistical edge over time.

As we conclude this module, it's important to recognize that technical analysis is both an art and a science. The science lies in the mathematical calculations, the statistical patterns, and the systematic application of indicators and tools. The art lies in the interpretation, the integration of multiple signals, and the judgment required to apply technical analysis in real-world trading situations. Mastery of technical analysis requires developing both the scientific understanding of the tools and the artistic judgment to apply them effectively.

The journey through technical analysis is ongoing - markets evolve, new patterns emerge, and successful traders continuously refine their approaches. The concepts covered in this module provide the foundation for that journey, but true mastery comes from practice, experience, and the willingness to learn from both successes and failures. Technical analysis, when applied with discipline, proper risk management, and realistic expectations, can be a powerful tool for navigating equity markets and making informed trading decisions.


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