Here's a Python implementation to detect bullish falling wedge patterns in OHLCV data:
python
import pandas as pd
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
from typing import List, Tuple, Optional
def find_swing_points(data: pd.Series, window: int = 5) -> Tuple[List[int], List[int]]:
"""
Find swing highs and lows in price data
"""
highs = []
lows = []
for i in range(window, len(data) - window):
# Check for swing high
if all(data.iloc[i] >= data.iloc[i-j] for j in range(1, window+1)) and \
all(data.iloc[i] >= data.iloc[i+j] for j in range(1, window+1)):
highs.append(i)
# Check for swing low
if all(data.iloc[i] <= data.iloc[i-j] for j in range(1, window+1)) and \
all(data.iloc[i] <= data.iloc[i+j] for j in range(1, window+1)):
lows.append(i)
return highs, lows
def fit_trendline(x_coords: List[int], y_coords: List[float]) -> Tuple[float, float, float]:
"""
Fit a trend line and return slope, intercept, and R-squared
"""
if len(x_coords) < 2:
return 0, 0, 0
slope, intercept, r_value, _, _ = stats.linregress(x_coords, y_coords)
return slope, intercept, r_value**2
def detect_falling_wedge(df: pd.DataFrame,
lookback_period: int = 50,
min_touches: int = 3,
min_r_squared: float = 0.7,
volume_confirmation: bool = True) -> List[dict]:
"""
Detect falling wedge patterns in OHLCV data
Parameters:
- df: DataFrame with OHLCV data
- lookback_period: Number of periods to look back for pattern
- min_touches: Minimum number of touches on each trend line
- min_r_squared: Minimum R-squared for trend line validity
- volume_confirmation: Whether to check for decreasing volume
"""
patterns = []
# Ensure required columns exist
required_cols = ['High', 'Low', 'Close', 'Volume']
if not all(col in df.columns for col in required_cols):
raise ValueError(f"DataFrame must contain columns: {required_cols}")
for i in range(lookback_period, len(df) - 10): # Leave some room for breakout detection
# Get data window
window_data = df.iloc[i-lookback_period:i+10].copy()
window_data = window_data.reset_index(drop=True)
# Find swing points
highs, lows = find_swing_points(window_data['High'], window=3)
swing_lows_idx, _ = find_swing_points(window_data['Low'], window=3)
# Filter to get recent swing points
recent_highs = [h for h in highs if h < lookback_period]
recent_lows = [l for l in swing_lows_idx if l < lookback_period]
if len(recent_highs) < min_touches or len(recent_lows) < min_touches:
continue
# Take the most recent swing points
recent_highs = recent_highs[-min_touches-2:]
recent_lows = recent_lows[-min_touches-2:]
# Fit trend lines
high_prices = [window_data['High'].iloc[idx] for idx in recent_highs]
low_prices = [window_data['Low'].iloc[idx] for idx in recent_lows]
upper_slope, upper_intercept, upper_r2 = fit_trendline(recent_highs, high_prices)
lower_slope, lower_intercept, lower_r2 = fit_trendline(recent_lows, low_prices)
# Check falling wedge conditions
if (upper_slope < 0 and lower_slope < 0 and # Both lines sloping down
upper_slope < lower_slope and # Upper line steeper than lower
upper_r2 >= min_r_squared and lower_r2 >= min_r_squared): # Good fit
# Check for convergence
start_idx = min(recent_highs[0], recent_lows[0])
end_idx = lookback_period - 1
start_upper = upper_slope * start_idx + upper_intercept
start_lower = lower_slope * start_idx + lower_intercept
end_upper = upper_slope * end_idx + upper_intercept
end_lower = lower_slope * end_idx + lower_intercept
# Lines should be converging
if (end_upper - end_lower) < (start_upper - start_lower):
# Volume confirmation (optional)
volume_decreasing = True
if volume_confirmation:
recent_volume = window_data['Volume'].iloc[-10:].values
volume_slope, _, _ = fit_trendline(list(range(len(recent_volume))), recent_volume)
volume_decreasing = volume_slope < 0
# Check for potential breakout
current_price = window_data['Close'].iloc[lookback_period-1]
resistance_level = upper_slope * (lookback_period-1) + upper_intercept
pattern = {
'start_date': df.index[i-lookback_period],
'end_date': df.index[i-1],
'breakout_date': df.index[i] if current_price > resistance_level else None,
'upper_slope': upper_slope,
'lower_slope': lower_slope,
'upper_r2': upper_r2,
'lower_r2': lower_r2,
'resistance_level': resistance_level,
'current_price': current_price,
'volume_decreasing': volume_decreasing,
'pattern_index': i
}
patterns.append(pattern)
return patterns
def plot_falling_wedge(df: pd.DataFrame, pattern: dict, periods_before: int = 20, periods_after: int = 10):
"""
Plot a detected falling wedge pattern
"""
start_idx = df.index.get_loc(pattern['start_date']) - periods_before
end_idx = df.index.get_loc(pattern['end_date']) + periods_after
plot_data = df.iloc[max(0, start_idx):min(len(df), end_idx)].copy()
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 8), height_ratios=[3, 1])
# Price chart
ax1.plot(plot_data.index, plot_data['Close'], label='Close Price', linewidth=1)
ax1.plot(plot_data.index, plot_data['High'], alpha=0.3, color='green')
ax1.plot(plot_data.index, plot_data['Low'], alpha=0.3, color='red')
# Draw trend lines
pattern_start = pattern['start_date']
pattern_end = pattern['end_date']
pattern_range = pd.date_range(pattern_start, pattern_end, freq='D')
if len(pattern_range) > 1:
x_numeric = np.arange(len(pattern_range))
upper_line = pattern['upper_slope'] * x_numeric + pattern['upper_intercept']
lower_line = pattern['lower_slope'] * x_numeric + pattern['lower_intercept']
ax1.plot(pattern_range, upper_line, 'r--', label='Resistance', linewidth=2)
ax1.plot(pattern_range, lower_line, 'g--', label='Support', linewidth=2)
# Mark breakout if exists
if pattern['breakout_date']:
ax1.axvline(x=pattern['breakout_date'], color='blue', linestyle=':',
label='Breakout', linewidth=2)
ax1.set_title(f'Falling Wedge Pattern - {pattern["start_date"].strftime("%Y-%m-%d")} to {pattern["end_date"].strftime("%Y-%m-%d")}')
ax1.set_ylabel('Price')
ax1.legend()
ax1.grid(True, alpha=0.3)
# Volume chart
ax2.bar(plot_data.index, plot_data['Volume'], alpha=0.7, color='blue')
ax2.set_ylabel('Volume')
ax2.set_xlabel('Date')
ax2.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
# Example usage
def example_usage():
# Create sample data (replace with your actual data)
dates = pd.date_range('2023-01-01', periods=200, freq='D')
np.random.seed(42)
# Simulate falling wedge pattern
base_price = 100
prices = []
volumes = []
for i in range(200):
# Create falling wedge pattern in the middle
if 50 <= i <= 120:
trend = -0.1 * (i - 50) # Downward trend
volatility = max(0.5, 2 - (i - 50) * 0.02) # Decreasing volatility
noise = np.random.normal(0, volatility)
price = base_price + trend + noise
volume = max(1000, 5000 - (i - 50) * 30) # Decreasing volume
else:
price = base_price + np.random.normal(0, 2)
volume = np.random.randint(3000, 8000)
prices.append(price)
volumes.append(volume + np.random.randint(-500, 500))
df = pd.DataFrame({
'Open': prices,
'High': [p + abs(np.random.normal(0, 0.5)) for p in prices],
'Low': [p - abs(np.random.normal(0, 0.5)) for p in prices],
'Close': prices,
'Volume': volumes
}, index=dates)
# Detect patterns
patterns = detect_falling_wedge(df, lookback_period=40, min_touches=2)
print(f"Found {len(patterns)} falling wedge patterns:")
for i, pattern in enumerate(patterns):
print(f"\nPattern {i+1}:")
print(f" Period: {pattern['start_date'].strftime('%Y-%m-%d')} to {pattern['end_date'].strftime('%Y-%m-%d')}")
print(f" Upper slope: {pattern['upper_slope']:.4f}")
print(f" Lower slope: {pattern['lower_slope']:.4f}")
print(f" Upper R²: {pattern['upper_r2']:.3f}")
print(f" Lower R²: {pattern['lower_r2']:.3f}")
print(f" Volume decreasing: {pattern['volume_decreasing']}")
if pattern['breakout_date']:
print(f" Breakout detected: {pattern['breakout_date'].strftime('%Y-%m-%d')}")
# Plot the first pattern if any found
if patterns:
plot_falling_wedge(df, patterns[0])
return df, patterns
# Run example
if __name__ == "__main__":
df, patterns = example_usage()
This implementation provides:
Key Features:
Identifies swing highs and lows in price data
Fits trend lines using linear regression
Checks for falling wedge criteria (both lines sloping down, upper line steeper)
Optional volume confirmation (decreasing volume)
Detects potential breakouts above resistance
Visualization of detected patterns
Parameters you can adjust:
lookback_period: How far back to look for patterns
min_touches: Minimum number of touches on trend lines
min_r_squared: Minimum R² for trend line validity
volume_confirmation: Whether to require decreasing volume
Usage with your data:
python
# Load your OHLCV data
df = pd.read_csv('your_data.csv', index_col=0, parse_dates=True)
# Detect patterns
patterns = detect_falling_wedge(df, lookback_period=50, min_touches=3)
# Plot patterns
for pattern in patterns:
plot_falling_wedge(df, pattern)
The code returns a list of detected patterns with details like slopes, R-squared values, and breakout information that you can use for further analysis or trading signals.