Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,17 +1,47 @@
|
|
| 1 |
import gradio as gr
|
|
|
|
| 2 |
import pandas as pd
|
| 3 |
import numpy as np
|
| 4 |
import matplotlib.pyplot as plt
|
| 5 |
import matplotlib.dates as mdates
|
| 6 |
from io import BytesIO
|
|
|
|
| 7 |
from PIL import Image
|
| 8 |
-
import requests
|
| 9 |
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
-
def calculate_ema(df, period):
|
| 13 |
return df['close'].ewm(span=period, adjust=False).mean()
|
| 14 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
def calculate_rsi(df, period=14):
|
| 16 |
delta = df['close'].diff()
|
| 17 |
gain = delta.clip(lower=0)
|
|
@@ -21,21 +51,6 @@ def calculate_rsi(df, period=14):
|
|
| 21 |
rs = avg_gain / avg_loss
|
| 22 |
return 100 - (100 / (1 + rs))
|
| 23 |
|
| 24 |
-
def calculate_supertrend(df, period=10, multiplier=3):
|
| 25 |
-
hl2 = (df['high'] + df['low']) / 2
|
| 26 |
-
atr = df['high'].rolling(period).max() - df['low'].rolling(period).min()
|
| 27 |
-
upperband = hl2 + (multiplier * atr)
|
| 28 |
-
lowerband = hl2 - (multiplier * atr)
|
| 29 |
-
trend = [True] * len(df)
|
| 30 |
-
for i in range(1, len(df)):
|
| 31 |
-
if df['close'].iloc[i] > upperband.iloc[i - 1]:
|
| 32 |
-
trend[i] = True
|
| 33 |
-
elif df['close'].iloc[i] < lowerband.iloc[i - 1]:
|
| 34 |
-
trend[i] = False
|
| 35 |
-
else:
|
| 36 |
-
trend[i] = trend[i - 1]
|
| 37 |
-
return trend
|
| 38 |
-
|
| 39 |
def detect_rsi_divergence(df):
|
| 40 |
df['rsi'] = calculate_rsi(df)
|
| 41 |
df['bullish_div'] = False
|
|
@@ -53,11 +68,8 @@ def detect_rsi_divergence(df):
|
|
| 53 |
df['rsi'].iloc[i] < df['rsi'].iloc[i - 1] < df['rsi'].iloc[i - 2]
|
| 54 |
):
|
| 55 |
df.at[df.index[i], 'bearish_div'] = True
|
| 56 |
-
|
| 57 |
return df
|
| 58 |
|
| 59 |
-
# ------------------- Signal Generator -------------------
|
| 60 |
-
|
| 61 |
def generate_combined_signal(df):
|
| 62 |
df['ema_50'] = calculate_ema(df, 50)
|
| 63 |
df['ema_200'] = calculate_ema(df, 200)
|
|
@@ -86,33 +98,28 @@ def generate_combined_signal(df):
|
|
| 86 |
signal += " + π Bearish RSI Divergence"
|
| 87 |
return signal
|
| 88 |
|
| 89 |
-
# ------------------- Chart Plotting -------------------
|
| 90 |
-
|
| 91 |
def plot_chart(df):
|
| 92 |
-
df = df.tail(50).copy()
|
| 93 |
df['timestamp'] = pd.to_datetime(df['timestamp'])
|
| 94 |
-
|
| 95 |
fig, ax = plt.subplots(figsize=(10, 5))
|
| 96 |
|
| 97 |
-
for
|
| 98 |
-
color = 'green' if
|
| 99 |
-
ax.plot([
|
| 100 |
-
ax.plot([
|
| 101 |
|
| 102 |
-
ax.plot(df['timestamp'], df
|
| 103 |
-
ax.plot(df['timestamp'], df
|
| 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', fontsize=12, ha='center')
|
| 108 |
-
if df['bearish_div'].iloc[i]:
|
| 109 |
ax.annotate('β', (df['timestamp'].iloc[i], df['high'].iloc[i] + 1), color='red', fontsize=12, ha='center')
|
| 110 |
|
| 111 |
-
ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))
|
| 112 |
-
ax.
|
| 113 |
plt.xticks(rotation=45)
|
| 114 |
-
plt.title(
|
| 115 |
-
plt.legend()
|
| 116 |
plt.tight_layout()
|
| 117 |
|
| 118 |
buf = BytesIO()
|
|
@@ -121,34 +128,25 @@ def plot_chart(df):
|
|
| 121 |
plt.close(fig)
|
| 122 |
return Image.open(buf)
|
| 123 |
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
symbols = ['BTCUSDT', 'ETHUSDT', 'BNBUSDT', 'SOLUSDT', 'MATICUSDT']
|
| 147 |
-
|
| 148 |
-
dropdown = gr.Dropdown(choices=symbols, label="Select Trading Pair", value='BTCUSDT')
|
| 149 |
-
output_text = gr.Textbox(label="Signal")
|
| 150 |
-
output_chart = gr.Image(label="Chart")
|
| 151 |
-
|
| 152 |
-
app = gr.Interface(fn=analyze, inputs=dropdown, outputs=[output_text, output_chart], title="Crypto Signal Generator", live=True)
|
| 153 |
-
|
| 154 |
-
app.launch()
|
|
|
|
| 1 |
import gradio as gr
|
| 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 |
+
def get_price_data(symbol="BTCUSDT", interval="1h", limit=100):
|
| 12 |
+
url = f"https://api.mexc.com/api/v3/klines?symbol={symbol}&interval={interval}&limit={limit}"
|
| 13 |
+
response = requests.get(url)
|
| 14 |
+
data = response.json()
|
| 15 |
+
df = pd.DataFrame(data, columns=[
|
| 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 |
+
def calculate_ema(df, period=20):
|
| 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'].rolling(period).max() - df['low'].rolling(period).min()
|
| 30 |
+
atr = atr.rolling(period).mean()
|
| 31 |
+
upper_band = hl2 + (multiplier * atr)
|
| 32 |
+
lower_band = hl2 - (multiplier * atr)
|
| 33 |
+
supertrend = [True] * len(df)
|
| 34 |
+
|
| 35 |
+
for i in range(1, len(df)):
|
| 36 |
+
if df['close'][i] > upper_band[i - 1]:
|
| 37 |
+
supertrend[i] = True
|
| 38 |
+
elif df['close'][i] < lower_band[i - 1]:
|
| 39 |
+
supertrend[i] = False
|
| 40 |
+
else:
|
| 41 |
+
supertrend[i] = supertrend[i - 1]
|
| 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)
|
|
|
|
| 51 |
rs = avg_gain / avg_loss
|
| 52 |
return 100 - (100 / (1 + rs))
|
| 53 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
def detect_rsi_divergence(df):
|
| 55 |
df['rsi'] = calculate_rsi(df)
|
| 56 |
df['bullish_div'] = False
|
|
|
|
| 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 |
def generate_combined_signal(df):
|
| 74 |
df['ema_50'] = calculate_ema(df, 50)
|
| 75 |
df['ema_200'] = calculate_ema(df, 200)
|
|
|
|
| 98 |
signal += " + π Bearish RSI Divergence"
|
| 99 |
return signal
|
| 100 |
|
|
|
|
|
|
|
| 101 |
def plot_chart(df):
|
|
|
|
| 102 |
df['timestamp'] = pd.to_datetime(df['timestamp'])
|
|
|
|
| 103 |
fig, ax = plt.subplots(figsize=(10, 5))
|
| 104 |
|
| 105 |
+
for i in range(len(df)):
|
| 106 |
+
color = 'green' if df['close'].iloc[i] >= df['open'].iloc[i] else 'red'
|
| 107 |
+
ax.plot([df['timestamp'].iloc[i]] * 2, [df['low'].iloc[i], df['high'].iloc[i]], color='black')
|
| 108 |
+
ax.plot([df['timestamp'].iloc[i]] * 2, [df['open'].iloc[i], df['close'].iloc[i]], color=color, linewidth=5)
|
| 109 |
|
| 110 |
+
ax.plot(df['timestamp'], calculate_ema(df, 50), label="EMA 50", color='blue')
|
| 111 |
+
ax.plot(df['timestamp'], calculate_ema(df, 200), label="EMA 200", color='orange')
|
| 112 |
|
| 113 |
for i in range(len(df)):
|
| 114 |
+
if 'bullish_div' in df.columns and df['bullish_div'].iloc[i]:
|
| 115 |
ax.annotate('β', (df['timestamp'].iloc[i], df['low'].iloc[i] - 1), color='green', fontsize=12, ha='center')
|
| 116 |
+
if 'bearish_div' in df.columns and df['bearish_div'].iloc[i]:
|
| 117 |
ax.annotate('β', (df['timestamp'].iloc[i], df['high'].iloc[i] + 1), color='red', fontsize=12, ha='center')
|
| 118 |
|
| 119 |
+
ax.xaxis.set_major_formatter(mdates.DateFormatter('%m-%d %H:%M'))
|
| 120 |
+
ax.legend()
|
| 121 |
plt.xticks(rotation=45)
|
| 122 |
+
plt.title("MEXC Price Chart")
|
|
|
|
| 123 |
plt.tight_layout()
|
| 124 |
|
| 125 |
buf = BytesIO()
|
|
|
|
| 128 |
plt.close(fig)
|
| 129 |
return Image.open(buf)
|
| 130 |
|
| 131 |
+
def analyze(symbol, interval):
|
| 132 |
+
try:
|
| 133 |
+
df = get_price_data(symbol.upper(), interval)
|
| 134 |
+
signal = generate_combined_signal(df)
|
| 135 |
+
chart = plot_chart(df)
|
| 136 |
+
return signal, chart
|
| 137 |
+
except Exception as e:
|
| 138 |
+
return f"β Error: {e}", None
|
| 139 |
+
|
| 140 |
+
symbol_input = gr.Textbox(label="Symbol", value="BTCUSDT")
|
| 141 |
+
interval_input = gr.Dropdown(["1m", "5m", "15m", "1h", "4h", "1d"], label="Interval", value="1h")
|
| 142 |
+
|
| 143 |
+
iface = gr.Interface(
|
| 144 |
+
fn=analyze,
|
| 145 |
+
inputs=[symbol_input, interval_input],
|
| 146 |
+
outputs=["text", "image"],
|
| 147 |
+
title="π Crypto Signal Generator",
|
| 148 |
+
description="EMA + SuperTrend + RSI Divergence on MEXC Data"
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
if __name__ == "__main__":
|
| 152 |
+
iface.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|