Can somebody help me in elliot wave code please
Hi @Siya2211 ,
Refer the below code:
import pandas as pd
import numpy as np
def elliott_wave(df, swing_tolerance=0.02):
"""
:df: Pandas DataFrame with columns ['timestamp', 'open', 'high', 'low', 'close']
:swing_tolerance: Minimum % price change to consider a swing
"""
if len(df) < 30:
return {"error": "Not enough data to calculate Elliott Waves"}
closes = df['close'].values
timestamps = df['timestamp'].values
# Find pivots (zigzag)
pivots = []
last_pivot_price = closes[0]
last_pivot_index = 0
direction = 0 # 1 = up, -1 = down, 0 = undefined
for i in range(1, len(closes)):
change = (closes[i] - last_pivot_price) / last_pivot_price
if abs(change) >= swing_tolerance:
new_direction = 1 if closes[i] > last_pivot_price else -1
if direction != 0 and new_direction == direction:
continue
pivots.append((i, closes[i], timestamps[i]))
last_pivot_price = closes[i]
last_pivot_index = i
direction = new_direction
# Assign Elliott Waves: W1-W5 and A-B-C if enough pivots
waves = {}
labels = ["W1", "W2", "W3", "W4", "W5", "A", "B", "C"]
for idx, pivot in enumerate(pivots[:len(labels)]):
wave_label = labels[idx]
waves[wave_label] = {
"index": pivot[0],
"price": pivot[1],
"timestamp": pivot[2]
}
return {
"waves": waves,
"pivots": pivots,
"total_pivots": len(pivots)
}
# Example
data = {
"timestamp": pd.date_range("2025-01-01", periods=60, freq="D"),
"open": np.random.uniform(100, 200, 60),
"high": np.random.uniform(105, 205, 60),
"low": np.random.uniform(95, 195, 60),
"close": np.random.uniform(100, 200, 60)
}
df = pd.DataFrame(data)
result = elliott_wave(df, swing_tolerance=0.03)