Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,47 +1,40 @@
|
|
| 1 |
-
import
|
| 2 |
-
import requests
|
| 3 |
import pandas as pd
|
| 4 |
-
import numpy as np
|
| 5 |
import matplotlib.pyplot as plt
|
| 6 |
import matplotlib.dates as mdates
|
| 7 |
from io import BytesIO
|
| 8 |
-
from datetime import datetime
|
| 9 |
from PIL import Image
|
|
|
|
| 10 |
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
df = pd.DataFrame(
|
| 16 |
-
'timestamp', 'open', 'high', 'low', 'close', 'volume',
|
| 17 |
-
'close_time', 'quote_asset_volume', 'number_of_trades',
|
| 18 |
-
'taker_buy_base_vol', 'taker_buy_quote_vol', 'ignore'
|
| 19 |
-
])
|
| 20 |
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
|
| 21 |
-
df = df[['timestamp', 'open', 'high', 'low', 'close', 'volume']].astype(float)
|
| 22 |
return df
|
| 23 |
|
| 24 |
-
|
|
|
|
| 25 |
return df['close'].ewm(span=period, adjust=False).mean()
|
| 26 |
|
|
|
|
| 27 |
def calculate_supertrend(df, period=10, multiplier=3):
|
| 28 |
hl2 = (df['high'] + df['low']) / 2
|
| 29 |
-
atr = df['high']
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
supertrend = [True] * len(df)
|
| 34 |
-
|
| 35 |
for i in range(1, len(df)):
|
| 36 |
-
if df['close'][i] >
|
| 37 |
-
|
| 38 |
-
elif df['close'][i] <
|
| 39 |
-
|
| 40 |
else:
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
return pd.Series(supertrend)
|
| 44 |
|
|
|
|
| 45 |
def calculate_rsi(df, period=14):
|
| 46 |
delta = df['close'].diff()
|
| 47 |
gain = delta.clip(lower=0)
|
|
@@ -55,71 +48,70 @@ def detect_rsi_divergence(df):
|
|
| 55 |
df['rsi'] = calculate_rsi(df)
|
| 56 |
df['bullish_div'] = False
|
| 57 |
df['bearish_div'] = False
|
| 58 |
-
|
| 59 |
for i in range(2, len(df)):
|
| 60 |
-
if (
|
| 61 |
-
df['
|
| 62 |
-
df['rsi'].iloc[i] > df['rsi'].iloc[i - 1] > df['rsi'].iloc[i - 2]
|
| 63 |
-
):
|
| 64 |
df.at[df.index[i], 'bullish_div'] = True
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
df['close'].iloc[i] > df['close'].iloc[i - 1] > df['close'].iloc[i - 2] and
|
| 68 |
-
df['rsi'].iloc[i] < df['rsi'].iloc[i - 1] < df['rsi'].iloc[i - 2]
|
| 69 |
-
):
|
| 70 |
df.at[df.index[i], 'bearish_div'] = True
|
| 71 |
return df
|
| 72 |
|
| 73 |
-
|
|
|
|
| 74 |
df['ema_50'] = calculate_ema(df, 50)
|
| 75 |
df['ema_200'] = calculate_ema(df, 200)
|
| 76 |
df['supertrend'] = calculate_supertrend(df)
|
| 77 |
df = detect_rsi_divergence(df)
|
| 78 |
|
| 79 |
if df[['ema_50', 'ema_200']].isna().any().any():
|
| 80 |
-
return "β οΈ Not enough data for
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
signal = f"β οΈ {ema_signal}"
|
| 92 |
else:
|
| 93 |
-
|
| 94 |
|
| 95 |
if df['bullish_div'].iloc[-1]:
|
| 96 |
-
|
| 97 |
if df['bearish_div'].iloc[-1]:
|
| 98 |
-
|
| 99 |
-
return
|
| 100 |
|
|
|
|
| 101 |
def plot_chart(df):
|
| 102 |
-
df
|
| 103 |
-
|
|
|
|
|
|
|
|
|
|
| 104 |
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
ax.plot([
|
|
|
|
| 109 |
|
| 110 |
-
ax.plot(df['timestamp'],
|
| 111 |
-
ax.plot(df['timestamp'],
|
| 112 |
|
| 113 |
for i in range(len(df)):
|
| 114 |
-
if
|
| 115 |
-
ax.annotate('β', (df['timestamp'].iloc[i], df['low'].iloc[i] - 1), color='green',
|
| 116 |
-
if
|
| 117 |
-
ax.annotate('β', (df['timestamp'].iloc[i], df['high'].iloc[i] + 1), color='red',
|
| 118 |
|
| 119 |
ax.xaxis.set_major_formatter(mdates.DateFormatter('%m-%d %H:%M'))
|
| 120 |
-
ax.legend()
|
| 121 |
plt.xticks(rotation=45)
|
| 122 |
-
|
|
|
|
| 123 |
plt.tight_layout()
|
| 124 |
|
| 125 |
buf = BytesIO()
|
|
@@ -128,25 +120,25 @@ def plot_chart(df):
|
|
| 128 |
plt.close(fig)
|
| 129 |
return Image.open(buf)
|
| 130 |
|
| 131 |
-
|
|
|
|
| 132 |
try:
|
| 133 |
-
df =
|
| 134 |
-
|
|
|
|
|
|
|
| 135 |
chart = plot_chart(df)
|
| 136 |
return signal, chart
|
| 137 |
except Exception as e:
|
| 138 |
return f"β Error: {e}", None
|
| 139 |
|
| 140 |
-
|
| 141 |
-
|
| 142 |
|
| 143 |
-
|
| 144 |
fn=analyze,
|
| 145 |
-
inputs=[
|
| 146 |
-
outputs=["
|
| 147 |
-
title="
|
| 148 |
-
description="
|
| 149 |
-
)
|
| 150 |
-
|
| 151 |
-
if __name__ == "__main__":
|
| 152 |
-
iface.launch()
|
|
|
|
| 1 |
+
import ccxt
|
|
|
|
| 2 |
import pandas as pd
|
|
|
|
| 3 |
import matplotlib.pyplot as plt
|
| 4 |
import matplotlib.dates as mdates
|
| 5 |
from io import BytesIO
|
|
|
|
| 6 |
from PIL import Image
|
| 7 |
+
import gradio as gr
|
| 8 |
|
| 9 |
+
# Fetch OHLCV from MEXC
|
| 10 |
+
def fetch_ohlcv(symbol='BTC/USDT', timeframe='1h', limit=150):
|
| 11 |
+
exchange = ccxt.mexc()
|
| 12 |
+
ohlcv = exchange.fetch_ohlcv(symbol, timeframe=timeframe, limit=limit)
|
| 13 |
+
df = pd.DataFrame(ohlcv, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
|
|
|
|
| 15 |
return df
|
| 16 |
|
| 17 |
+
# EMA calculation
|
| 18 |
+
def calculate_ema(df, period):
|
| 19 |
return df['close'].ewm(span=period, adjust=False).mean()
|
| 20 |
|
| 21 |
+
# SuperTrend indicator
|
| 22 |
def calculate_supertrend(df, period=10, multiplier=3):
|
| 23 |
hl2 = (df['high'] + df['low']) / 2
|
| 24 |
+
atr = (df['high'] - df['low']).rolling(period).mean()
|
| 25 |
+
upper = hl2 + multiplier * atr
|
| 26 |
+
lower = hl2 - multiplier * atr
|
| 27 |
+
st = [True] * len(df)
|
|
|
|
|
|
|
| 28 |
for i in range(1, len(df)):
|
| 29 |
+
if df['close'].iloc[i] > upper.iloc[i - 1]:
|
| 30 |
+
st[i] = True
|
| 31 |
+
elif df['close'].iloc[i] < lower.iloc[i - 1]:
|
| 32 |
+
st[i] = False
|
| 33 |
else:
|
| 34 |
+
st[i] = st[i - 1]
|
| 35 |
+
return pd.Series(st, index=df.index)
|
|
|
|
| 36 |
|
| 37 |
+
# RSI + divergence detection
|
| 38 |
def calculate_rsi(df, period=14):
|
| 39 |
delta = df['close'].diff()
|
| 40 |
gain = delta.clip(lower=0)
|
|
|
|
| 48 |
df['rsi'] = calculate_rsi(df)
|
| 49 |
df['bullish_div'] = False
|
| 50 |
df['bearish_div'] = False
|
|
|
|
| 51 |
for i in range(2, len(df)):
|
| 52 |
+
if (df['close'].iloc[i] < df['close'].iloc[i-1] < df['close'].iloc[i-2] and
|
| 53 |
+
df['rsi'].iloc[i] > df['rsi'].iloc[i-1] > df['rsi'].iloc[i-2]):
|
|
|
|
|
|
|
| 54 |
df.at[df.index[i], 'bullish_div'] = True
|
| 55 |
+
if (df['close'].iloc[i] > df['close'].iloc[i-1] > df['close'].iloc[i-2] and
|
| 56 |
+
df['rsi'].iloc[i] < df['rsi'].iloc[i-1] < df['rsi'].iloc[i-2]):
|
|
|
|
|
|
|
|
|
|
| 57 |
df.at[df.index[i], 'bearish_div'] = True
|
| 58 |
return df
|
| 59 |
|
| 60 |
+
# Combined signal logic
|
| 61 |
+
def generate_signal(df):
|
| 62 |
df['ema_50'] = calculate_ema(df, 50)
|
| 63 |
df['ema_200'] = calculate_ema(df, 200)
|
| 64 |
df['supertrend'] = calculate_supertrend(df)
|
| 65 |
df = detect_rsi_divergence(df)
|
| 66 |
|
| 67 |
if df[['ema_50', 'ema_200']].isna().any().any():
|
| 68 |
+
return "β οΈ Not enough data for EMA"
|
| 69 |
+
|
| 70 |
+
ema_sig = 'BULLISH' if df['ema_50'].iloc[-1] > df['ema_200'].iloc[-1] else 'BEARISH'
|
| 71 |
+
st_sig = 'BULLISH' if df['supertrend'].iloc[-1] else 'BEARISH'
|
| 72 |
+
|
| 73 |
+
if ema_sig == 'BULLISH' and st_sig == 'BULLISH':
|
| 74 |
+
label = "π₯ STRONG BUY"
|
| 75 |
+
elif ema_sig == 'BEARISH' and st_sig == 'BEARISH':
|
| 76 |
+
label = "π STRONG SELL"
|
| 77 |
+
elif ema_sig == st_sig:
|
| 78 |
+
label = f"β οΈ {ema_sig}"
|
|
|
|
| 79 |
else:
|
| 80 |
+
label = "π€ NEUTRAL / HOLD"
|
| 81 |
|
| 82 |
if df['bullish_div'].iloc[-1]:
|
| 83 |
+
label += " + π Bullish RSI Divergence"
|
| 84 |
if df['bearish_div'].iloc[-1]:
|
| 85 |
+
label += " + π Bearish RSI Divergence"
|
| 86 |
+
return label
|
| 87 |
|
| 88 |
+
# Plot chart and overlays
|
| 89 |
def plot_chart(df):
|
| 90 |
+
df = df.tail(100).copy()
|
| 91 |
+
df['ema_50'] = calculate_ema(df, 50)
|
| 92 |
+
df['ema_200'] = calculate_ema(df, 200)
|
| 93 |
+
df['supertrend'] = calculate_supertrend(df)
|
| 94 |
+
df = detect_rsi_divergence(df)
|
| 95 |
|
| 96 |
+
fig, ax = plt.subplots(figsize=(10, 5))
|
| 97 |
+
for _, row in df.iterrows():
|
| 98 |
+
color = 'green' if row['close'] >= row['open'] else 'red'
|
| 99 |
+
ax.plot([row['timestamp'], row['timestamp']], [row['low'], row['high']], color='black', linewidth=1)
|
| 100 |
+
ax.plot([row['timestamp'], row['timestamp']], [row['open'], row['close']], color=color, linewidth=4)
|
| 101 |
|
| 102 |
+
ax.plot(df['timestamp'], df['ema_50'], label='EMA 50', color='orange')
|
| 103 |
+
ax.plot(df['timestamp'], df['ema_200'], label='EMA 200', color='purple')
|
| 104 |
|
| 105 |
for i in range(len(df)):
|
| 106 |
+
if df['bullish_div'].iloc[i]:
|
| 107 |
+
ax.annotate('β', (df['timestamp'].iloc[i], df['low'].iloc[i] - 1), color='green', ha='center')
|
| 108 |
+
if df['bearish_div'].iloc[i]:
|
| 109 |
+
ax.annotate('β', (df['timestamp'].iloc[i], df['high'].iloc[i] + 1), color='red', ha='center')
|
| 110 |
|
| 111 |
ax.xaxis.set_major_formatter(mdates.DateFormatter('%m-%d %H:%M'))
|
|
|
|
| 112 |
plt.xticks(rotation=45)
|
| 113 |
+
ax.legend()
|
| 114 |
+
plt.title("Price - EMA, SuperTrend & RSI Divergence")
|
| 115 |
plt.tight_layout()
|
| 116 |
|
| 117 |
buf = BytesIO()
|
|
|
|
| 120 |
plt.close(fig)
|
| 121 |
return Image.open(buf)
|
| 122 |
|
| 123 |
+
# Gradio interface
|
| 124 |
+
def analyze(pair, timeframe):
|
| 125 |
try:
|
| 126 |
+
df = fetch_ohlcv(pair, timeframe)
|
| 127 |
+
if df.empty or len(df) < 60:
|
| 128 |
+
return "β Not enough data", None
|
| 129 |
+
signal = generate_signal(df)
|
| 130 |
chart = plot_chart(df)
|
| 131 |
return signal, chart
|
| 132 |
except Exception as e:
|
| 133 |
return f"β Error: {e}", None
|
| 134 |
|
| 135 |
+
pairs = ['BTC/USDT', 'ETH/USDT', 'MX/USDT', 'SOL/USDT']
|
| 136 |
+
timeframes = ['1m', '5m', '15m', '1h', '4h']
|
| 137 |
|
| 138 |
+
gr.Interface(
|
| 139 |
fn=analyze,
|
| 140 |
+
inputs=[gr.Dropdown(pairs, label="Trading Pair"), gr.Dropdown(timeframes, label="Timeframe")],
|
| 141 |
+
outputs=[gr.Text(label="Signal"), gr.Image(label="Chart")],
|
| 142 |
+
title="Crypto Signal Generator (MEXC EMA + SuperTrend + RSI Div)",
|
| 143 |
+
description="Select a pair and timeframe to view technical signal and chart."
|
| 144 |
+
).launch()
|
|
|
|
|
|
|
|
|