Elliott Wave Python Code 【FULL - Summary】
if len(waves) < 5: return {'pattern': 'none', 'waves': waves, 'valid': False, 'reason': 'Not enough swing points'}
def fibonacci_ratios(self, wave: Dict) -> Dict: """Calculate Fibonacci retracements/extensions for a wave.""" mag = wave['magnitude'] return { '0.382': mag * 0.382, '0.5': mag * 0.5, '0.618': mag * 0.618, '1.0': mag, '1.272': mag * 1.272, '1.618': mag * 1.618, }
# Annotate wave numbers (first 5 waves if exist) waves = result['waves'] for i, wave in enumerate(waves[:5]): mid_idx = (wave['start_idx'] + wave['end_idx']) // 2 mid_price = (wave['start_price'] + wave['end_price']) / 2 plt.text(mid_idx, mid_price, str(i+1), fontsize=12, fontweight='bold', bbox=dict(facecolor='yellow', alpha=0.7))
def detect_elliott_waves(self, prices: np.ndarray) -> Dict: """ Main function: returns detected wave structure and validation. """ swings_df = self.find_swing_points(prices) waves = self.label_swing_waves(swings_df) elliott wave python code
detector = ElliottWaveDetector(swing_window=8) result = detector.detect_elliott_waves(price_series)
class ElliottWaveDetector: def (self, swing_window: int = 5): """ Parameters: ----------- swing_window : int Window size for identifying local extrema (swing highs/lows). """ self.swing_window = swing_window self.waves = []
waves = [] for i in range(len(swings_df) - 1): start = swings_df.iloc[i] end = swings_df.iloc[i+1] wave = { 'start_idx': start['index'], 'end_idx': end['index'], 'start_price': start['price'], 'end_price': end['price'], 'direction': 'up' if end['price'] > start['price'] else 'down', 'magnitude': abs(end['price'] - start['price']), 'start_type': start['type'], 'end_type': end['type'], } waves.append(wave) return waves if len(waves) < 5: return {'pattern': 'none', 'waves':
if impulse_ok: pattern_type = 'impulse_5wave' elif corrective_ok: pattern_type = 'corrective_abc' else: pattern_type = 'unclear'
def find_swing_points(self, prices: np.ndarray) -> pd.DataFrame: """Identify swing highs and lows.""" highs = argrelextrema(prices, np.greater, order=self.swing_window)[0] lows = argrelextrema(prices, np.less, order=self.swing_window)[0]
# Add Fibonacci ratio estimates for key waves fibs = {} if len(waves) >= 3: fibs['wave3_extension'] = self.fibonacci_ratios(waves[2]) # wave 3 if len(waves) >= 5: fibs['wave5_target'] = self.fibonacci_ratios(waves[4])['1.618'] if len(waves) <
return { 'pattern': pattern_type, 'waves': waves, 'valid': impulse_ok or corrective_ok, 'fibonacci_levels': fibs, 'swing_points': swings_df } Example usage & visualization ------------------------------- if name == " main ": import matplotlib.pyplot as plt
# Plotting plt.figure(figsize=(14, 6)) plt.plot(price_series, label='Price', color='black', alpha=0.6)
swings = sorted(swings, key=lambda x: x['index']) return pd.DataFrame(swings)
swings = [] for idx in highs: swings.append({'index': idx, 'price': prices[idx], 'type': 'high'}) for idx in lows: swings.append({'index': idx, 'price': prices[idx], 'type': 'low'})