Okay, let's write Python code to find a bullish falling wedge pattern in OHLCV data.
A bullish falling wedge is characterized by:
- Downward Trend: The price generally moves downwards.
- Converging Trendlines: The price action is contained between two downward-sloping lines that are coming closer together.
- Lower Highs: The upper trendline connects a series of lower highs.
- Lower Lows: The lower trendline connects a series of lower lows.
- Convergence: The slope of the upper line is steeper (more negative) than the slope of the lower line.
- Breakout: The pattern is confirmed when the price breaks convincingly above the upper trendline, ideally with increasing volume.
This is a complex pattern to detect algorithmically because identifying the "correct" trendlines is subjective and requires finding significant pivot points. We'll use scipy.signal.find_peaks to identify potential swing highs and lows, and then try to fit lines through these points to see if they form a valid falling wedge.
Steps:
- Identify significant swing highs using
find_peaks on the 'High' series.
- Identify significant swing lows using
find_peaks on the negative of the 'Low' series.
- Iterate through recent price history (a lookback window).
- Within the window, identify candidate upper trendlines connecting a recent high pivot to an earlier high pivot.
- Within the window, identify candidate lower trendlines connecting a recent low pivot to an earlier low pivot.
- Check if a pair of candidate lines forms a valid falling wedge (downward sloping, converging, separated, sufficient duration).
- If a wedge is found, check subsequent bars for a bullish breakout (close above the upper trendline).
Parameters for Tuning:
lookback: How many bars to look back to find the pattern.
peak_prominence: A parameter for find_peaks controlling how significant a peak/trough must be to be considered a pivot point. Higher values find fewer, more significant pivots.
peak_distance: A parameter for find_peaks setting a minimum number of bars between detected peaks/troughs. Helps filter out noise.
min_wedge_duration: Minimum number of bars the wedge pattern must span.
breakout_lookahead: How many bars after the potential wedge completion to look for a breakout.
breakout_multiple: How far above the upper trendline the close must be (e.g., 1.005 means 0.5% above).
Let's implement this in Python using pandas and scipy.
import pandas as pd
import numpy as np
from scipy.signal import find_peaks
from scipy.stats import linregress
import matplotlib.pyplot as plt # For visualization
def fit_line(x1, y1, x2, y2):
"""Fits a line between two points (x1, y1) and (x2, y2)."""
if x1 == x2: # Avoid division by zero
return np.nan, np.nan
slope = (y2 - y1) / (x2 - x1)
intercept = y1 - slope * x1
return slope, intercept
def line_value(x, slope, intercept):
"""Calculates the y value for a given x using slope and intercept."""
return slope * x + intercept
def find_bullish_falling_wedge(df, lookback=200, peak_prominence=0.005, peak_distance=10,
min_wedge_duration=30, breakout_lookahead=10, breakout_multiple=1.005):
"""
Finds bullish falling wedge patterns in OHLCV data.
Args:
df (pd.DataFrame): DataFrame with columns 'High', 'Low', 'Close'.
Index should be suitable for plotting (e.g., integer or datetime).
lookback (int): Number of bars to look back for pattern detection.
peak_prominence (float): Prominence parameter for scipy.signal.find_peaks
(as a percentage of price range in window).
peak_distance (int): Required minimum number of bars between peaks/troughs.
min_wedge_duration (int): Minimum number of bars required for the pattern duration.
breakout_lookahead (int): Number of bars to look for a breakout after pattern end.
breakout_multiple (float): Factor above upper trendline for breakout confirmation
(e.g., 1.005 for 0.5% above).
Returns:
list: A list of dictionaries, each representing a detected wedge breakout.
Each dict contains 'breakout_idx', 'wedge_start_idx', 'wedge_end_idx',
'upper_line', 'lower_line'.
"""
df = df.copy() # Work on a copy
# Ensure indices are integers for line fitting calculations
# We will store original indices in the output
temp_df = df.reset_index()
original_index_name = df.index.name if df.index.name is not None else 'original_index'
temp_df = temp_df.rename(columns={'index': original_index_name})
highs = temp_df['High'].values
lows = temp_df['Low'].values
closes = temp_df['Close'].values
detected_breakouts = []
# Loop through the DataFrame starting after the lookback period
for i in range(lookback, len(temp_df)):
window_start_idx = i - lookback
window_data = temp_df.iloc[window_start_idx : i + 1]
# --- 1. Find Peaks (Swing Highs) in the window ---
# Calculate prominence relative to the price range in the window
price_range = window_data['High'].max() - window_data['Low'].min()
current_peak_prominence = price_range * peak_prominence
# Find peaks relative to the window start
high_peak_indices_relative, properties = find_peaks(window_data['High'],
prominence=current_peak_prominence,
distance=peak_distance)
# Convert relative indices to global temporary df indices
high_peak_indices = window_data.iloc[high_peak_indices_relative].index.tolist()
# Filter peaks: Only consider peaks up to the current bar `i` as candidates
# for forming the *end* of the wedge pattern itself.
current_high_pivots = [idx for idx in high_peak_indices if idx <= i]
# --- 2. Find Troughs (Swing Lows) in the window ---
# find_peaks finds maxima, so use the negative of the 'Low' series to find minima
low_trough_indices_relative, properties = find_peaks(-window_data['Low'],
prominence=current_peak_prominence,
distance=peak_distance)
# Convert relative indices to global temporary df indices
low_trough_indices = window_data.iloc[low_trough_indices_relative].index.tolist()
# Filter troughs: Only consider troughs up to the current bar `i`
current_low_pivots = [idx for idx in low_trough_indices if idx <= i]
# Need at least 2 high pivots and 2 low pivots to form a wedge
if len(current_high_pivots) < 2 or len(current_low_pivots) < 2:
continue
# --- 3. Find the most recent relevant pivots ---
# The wedge pattern we are looking for often ends near the latest pivots
last_high_pivot_idx = max(current_high_pivots) if current_high_pivots else -1
last_low_pivot_idx = max(current_low_pivots) if current_low_pivots else -1
# If either last pivot is outside the reasonable end point (e.g., exactly at window start), skip
if last_high_pivot_idx < window_start_idx or last_low_pivot_idx < window_start_idx:
continue
# --- 4. Find candidate earlier pivots to form trendlines ---
# Find the *earliest* high pivot before last_high_pivot_idx that is higher
hp1_idx = None
for j in sorted(current_high_pivots, reverse=True): # Search backwards
if j < last_high_pivot_idx and highs[j] > highs[last_high_pivot_idx]:
# Check if there are no higher pivots between j and last_high_pivot_idx
intermediate_highs = [k for k in current_high_pivots if j < k < last_high_pivot_idx]
if all(highs[k] < line_value(k, *fit_line(j, highs[j], last_high_pivot_idx, highs[last_high_pivot_idx])) for k in intermediate_highs):
hp1_idx = j
break # Found the earliest valid start point
# Find the *earliest* low pivot before last_low_pivot_idx that is lower
lp1_idx = None
for j in sorted(current_low_pivots, reverse=True): # Search backwards
if j < last_low_pivot_idx and lows[j] < lows[last_low_pivot_idx]:
# Check if there are no lower pivots between j and last_low_pivot_idx
intermediate_lows = [k for k in current_low_pivots if j < k < last_low_pivot_idx]
if all(lows[k] > line_value(k, *fit_line(j, lows[j], last_low_pivot_idx, lows[last_low_pivot_idx])) for k in intermediate_lows):
lp1_idx = j
break # Found the earliest valid start point
# Need both starting pivots to form the lines
if hp1_idx is None or lp1_idx is None:
continue
# --- 5. Fit the trendlines ---
m_upper, c_upper = fit_line(hp1_idx, highs[hp1_idx], last_high_pivot_idx, highs[last_high_pivot_idx])
m_lower, c_lower = fit_line(lp1_idx, lows[lp1_idx], last_low_pivot_idx, lows[last_low_pivot_idx])
# --- 6. Check Wedge Criteria ---
wedge_start_idx = min(hp1_idx, lp1_idx)
wedge_end_idx = max(last_high_pivot_idx, last_low_pivot_idx)
# Criteria checks:
# a) Both slopes must be negative (falling)
# b) Upper slope must be more negative than lower slope (convergence)
# c) Upper line must be above lower line at the start of the potential wedge
# d) Pattern must meet minimum duration
is_falling = m_upper < 0 and m_lower < 0
is_converging = m_upper < m_lower # Upper line is steeper falling than lower line
is_separated_at_start = line_value(wedge_start_idx, m_upper, c_upper) > line_value(wedge_start_idx, m_lower, c_lower)
is_sufficient_duration = (wedge_end_idx - wedge_start_idx) >= min_wedge_duration
if is_falling and is_converging and is_separated_at_start and is_sufficient_duration:
# Potential wedge found ending around wedge_end_idx or index i
# Now check for breakout after the pattern completes
# Look for breakout bars starting from the bar *after* the wedge ended
for breakout_idx in range(wedge_end_idx + 1, min(i + breakout_lookahead + 1, len(temp_df))):
# Check if the close is above the extended upper trendline
extended_upper_val = line_value(breakout_idx, m_upper, c_upper)
if closes[breakout_idx] > extended_upper_val * breakout_multiple:
# Breakout confirmed!
detected_breakouts.append({
'breakout_idx': temp_df.loc[breakout_idx, original_index_name],
'wedge_start_idx': temp_df.loc[wedge_start_idx, original_index_name],
'wedge_end_idx': temp_df.loc[wedge_end_idx, original_index_name],
'upper_line': (m_upper, c_upper, hp1_idx, last_high_pivot_idx), # slope, intercept, start_fit_idx, end_fit_idx
'lower_line': (m_lower, c_lower, lp1_idx, last_low_pivot_idx), # slope, intercept, start_fit_idx, end_fit_idx
'pivot_highs': [temp_df.loc[p, original_index_name] for p in current_high_pivots if wedge_start_idx <= p <= wedge_end_idx],
'pivot_lows': [temp_df.loc[p, original_index_name] for p in current_low_pivots if wedge_start_idx <= p <= wedge_end_idx],
})
# Once a breakout is found for this wedge instance, stop looking for more breakouts for it
# to avoid multiple signals for the same pattern.
break # Exit the breakout search loop
return detected_breakouts
# --- Example Usage ---
if __name__ == '__main__':
# Create a sample OHLCV DataFrame with a potential falling wedge
# This is synthetic data for demonstration
data = {
'Date': pd.to_datetime(pd.date_range(start='2023-01-01', periods=200)),
'Open': np.linspace(100, 80, 200) + np.random.randn(200) * 2,
'High': np.linspace(102, 82, 200) + np.random.randn(200) * 2.5,
'Low': np.linspace(98, 78, 200) + np.random.randn(200) * 1.5,
'Close': np.linspace(100, 80, 200) + np.random.randn(200) * 2,
'Volume': np.random.randint(100000, 1000000, 200)
}
df = pd.DataFrame(data).set_index('Date')
# Manually adjust some points to simulate a falling wedge better
# Create a series of lower highs and lower lows that converge
df.loc[df.index[10:20], ['High', 'Close']] *= 0.98 # Initial dip
df.loc[df.index[30:40], ['Low', 'Close']] *= 0.97 # Lower low
df.loc[df.index[50:60], ['High', 'Close']] *= 0.96 # Lower high (less lower than previous high)
df.loc[df.index[70:80], ['Low', 'Close']] *= 0.965 # Lower low (less lower than previous low)
df.loc[df.index[90:100], ['High', 'Close']] *= 0.96 # Lower high
df.loc[df.index[110:120], ['Low', 'Close']] *= 0.96 # Lower low
# Introduce a potential breakout after bar 150
df.loc[df.index[150]:, 'Close'] = np.linspace(df['Close'].iloc[149], df['Close'].iloc[149] * 1.08, len(df.loc[df.index[150]:])) + np.random.randn(len(df.loc[df.index[150]:])) * 0.5
df.loc[df.index[150]:, 'High'] = df.loc[df.index[150]:, 'Close'] * 1.005
df.loc[df.index[150]:, 'Low'] = df.loc[df.index[150]:, 'Close'] * 0.995
print("Searching for bullish falling wedges...")
breakouts = find_bullish_falling_wedge(df, lookback=120, peak_prominence=0.005, peak_distance=5, min_wedge_duration=40, breakout_lookahead=10)
if breakouts:
print(f"Found {len(breakouts)} potential bullish falling wedge breakout(s):")
for b in breakouts:
print(f" Breakout at index: {b['breakout_idx']}")
print(f" Wedge period: {b['wedge_start_idx']} to {b['wedge_end_idx']}")
print(f" Upper line fit points (indices): {df.index[b['upper_line'][2]]}, {df.index[b['upper_line'][3]]}")
print(f" Lower line fit points (indices): {df.index[b['lower_line'][2]]}, {df.index[b['lower_line'][3]]}")
print("-" * 20)
# --- Optional: Visualize the first detected breakout ---
if breakouts:
first_breakout = breakouts[0]
wedge_start_idx = df.index.get_loc(first_breakout['wedge_start_idx'])
wedge_end_idx = df.index.get_loc(first_breakout['wedge_end_idx'])
breakout_idx = df.index.get_loc(first_breakout['breakout_idx'])
plt.figure(figsize=(15, 8))
plt.plot(df.index, df['Close'], label='Close', color='blue')
plt.plot(df.index, df['High'], label='High', color='cyan', linestyle='--', alpha=0.5)
plt.plot(df.index, df['Low'], label='Low', color='magenta', linestyle='--', alpha=0.5)
# Plot the wedge lines
m_u, c_u, hp1_idx_orig, hp2_idx_orig = first_breakout['upper_line']
m_l, c_l, lp1_idx_orig, lp2_idx_orig = first_breakout['lower_line']
# Convert original indices back to numerical indices for plotting
hp1_idx = df.index.get_loc(hp1_idx_orig)
hp2_idx = df.index.get_loc(hp2_idx_orig)
lp1_idx = df.index.get_loc(lp1_idx_orig)
lp2_idx = df.index.get_loc(lp2_idx_orig)
# Extend lines slightly for visualization
line_extend_bars = 10
plot_start = min(hp1_idx, lp1_idx)
plot_end = breakout_idx + line_extend_bars
x_range = np.arange(plot_start, plot_end + 1)
plt.plot(df.index[x_range], line_value(x_range, m_u, c_u), color='red', linestyle='-', label='Upper Trendline')
plt.plot(df.index[x_range], line_value(x_range, m_l, c_l), color='green', linestyle='-', label='Lower Trendline')
# Mark pivot points used for fitting
pivot_highs_plot_idx = [df.index.get_loc(p) for p in first_breakout['pivot_highs']]
pivot_lows_plot_idx = [df.index.get_loc(p) for p in first_breakout['pivot_lows']]
plt.scatter(df.index[pivot_highs_plot_idx], df['High'].iloc[pivot_highs_plot_idx], color='red', marker='o', label='High Pivots')
plt.scatter(df.index[pivot_lows_plot_idx], df['Low'].iloc[pivot_lows_plot_idx], color='green', marker='o', label='Low Pivots')
# Mark the breakout point
plt.scatter(df.index[breakout_idx], df['Close'].iloc[breakout_idx], color='purple', marker='^', s=100, label='Breakout')
plt.title('Bullish Falling Wedge Detection')
plt.xlabel('Date')
plt.ylabel('Price')
plt.legend()
plt.grid(True)
# Limit x-axis to the relevant window + breakout
plt.xlim(df.index[max(0, wedge_start_idx - line_extend_bars)], df.index[min(len(df)-1, breakout_idx + line_extend_bars)])
plt.show()
else:
print("No bullish falling wedge breakouts found.")
Explanation:
fit_line and line_value: Simple helper functions for basic linear algebra. We use the temporary integer index for calculations as it represents the sequential bar number, which is suitable for trendline fitting (y = m*x + c where x is the bar index).
find_bullish_falling_wedge Function:
- Takes the DataFrame and parameters as input.
- Creates a copy and resets the index to work with integer indices internally while preserving the original index (e.g., DatetimeIndex) for the output.
- It iterates through the DataFrame using a rolling
lookback window (for i in range(lookback, len(temp_df))). At each index i, it considers the data up to i.
- Pivot Detection:
scipy.signal.find_peaks is used on the High and (negative of) Low series within the current window (window_data). prominence and distance help filter for significant swings. The indices returned are relative to the window slice, so they are converted back to the global temporary DataFrame indices. Only pivots up to index i are considered for forming the end of the wedge.
- Trendline Candidate Selection: It finds the
last_high_pivot_idx and last_low_pivot_idx. It then searches backward from these points to find the earliest high pivot (hp1_idx) that is higher than last_high_pivot_idx and the earliest low pivot (lp1_idx) that is lower than last_low_pivot_idx. This heuristic attempts to find the two most extreme points defining the boundary ending at the recent pivot. A simple check is added to see if intermediate pivots are on the "correct" side of the potential line.
- Fit Lines: Lines are fitted using
fit_line between the chosen hp1_idx/last_high_pivot_idx and lp1_idx/last_low_pivot_idx.
- Wedge Criteria Check: It verifies the slopes are negative (
is_falling), the upper slope is more negative than the lower (is_converging), the lines are separated at the potential start point (is_separated_at_start), and the pattern duration is sufficient (is_sufficient_duration).
- Breakout Check: If a valid wedge geometry is found, it then searches the subsequent bars (or until the end of the data) starting from . If a price is found that is significantly above the extended upper trendline (), a breakout is confirmed.
Important Considerations:
- Parameter Tuning: The
lookback, peak_prominence, and peak_distance parameters are crucial. They heavily influence which swings are considered pivots and thus whether a wedge is detected. These parameters need to be tuned based on the specific instrument, timeframe, and desired sensitivity.
- Trendline Definition: The method used to find the starting points (
hp1_idx, lp1_idx) is a heuristic. Real-world trendlines can be subjective and might not always connect the latest pivot to the earliest higher/lower pivot. More complex methods exist but increase computational cost.
- Containment: This implementation doesn't explicitly check if the price action between the start and end pivots stays within the lines. The fact that the lines connect pivots implies some level of containment, but adding a check for this would make the detection more robust.
- Volume Confirmation: The code includes an optional mention of volume but doesn't implement a strict volume check for breakout confirmation, which is often a key part of wedge analysis. You could add a check like
df['Volume'].iloc[breakout_idx] > df['Volume'].iloc[wedge_end_idx:breakout_idx].mean() * volume_multiple.
- Overlapping/Redundant Signals: The current code might detect multiple breakouts for slightly different wedge patterns ending near the same time. Filtering overlapping patterns in the output might be necessary for practical trading.
- False Positives: As with any pattern detection, false positives are possible. This code provides potential signals that would require further analysis.
This code provides a solid framework for detecting bullish falling wedges based on geometric principles and pivot points. Remember to install the necessary libraries (pandas, numpy, scipy, matplotlib).