GoshawkVortexAI commited on
Commit
6148521
·
verified ·
1 Parent(s): ea3f43e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -88
app.py CHANGED
@@ -18,65 +18,64 @@ if api_key:
18
  client = Groq(api_key=api_key)
19
 
20
  # ==========================================
21
- # 📡 2. OKX PUBLIC API (Cloudflare engelini aşmak için)
22
  # ==========================================
23
- OKX_BASE = "https://www.okx.com/api/v5"
24
 
25
- # Cloudflare'in bot algılamasını azaltmak için tarayıcı benzeri başlıklar
26
- OKX_HEADERS = {
27
  "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
28
  "(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
29
  "Accept": "application/json",
30
  "Accept-Language": "en-US,en;q=0.9",
31
  }
32
 
33
- def fetch_okx_ticker(inst_id="BTC-USDT"):
34
- """OKX'ten anlık fiyat çeker. 3 kez dener, başarısızsa None döner."""
35
  for attempt in range(3):
36
  try:
37
  r = requests.get(
38
- f"{OKX_BASE}/market/ticker",
39
- params={"instId": inst_id},
40
- headers=OKX_HEADERS,
41
  timeout=15
42
  )
43
  r.raise_for_status()
44
- d = r.json()["data"][0]
45
  return {
46
- "last": float(d["last"]),
47
- "open24h": float(d["open24h"]),
48
- "high24h": float(d["high24h"]),
49
- "low24h": float(d["low24h"]),
50
- "vol24h": float(d["vol24h"]),
51
- "change_pct": (float(d["last"]) / float(d["open24h"]) - 1) * 100
52
  }
53
  except Exception as e:
54
- print(f"OKX ticker attempt {attempt+1} failed: {e}")
55
  if attempt < 2:
56
  time.sleep(2)
57
  return None
58
 
59
- def fetch_okx_candles(inst_id="BTC-USDT", bar="1H", limit=100):
60
- """OKX'ten mum verisi çeker. 3 kez dener, başarısızsa None döner."""
61
  for attempt in range(3):
62
  try:
63
  r = requests.get(
64
- f"{OKX_BASE}/market/candles",
65
- params={"instId": inst_id, "bar": bar, "limit": limit},
66
- headers=OKX_HEADERS,
67
  timeout=15
68
  )
69
  r.raise_for_status()
70
- raw = r.json()["data"]
71
- # OKX mum formatı: [ts, open, high, low, close, vol, ...]
72
- df = pd.DataFrame(raw, columns=["ts", "open", "high", "low", "close", "vol"])
73
- for col in ["open", "high", "low", "close", "vol"]:
74
- df[col] = df[col].astype(float)
75
  df["ts"] = pd.to_datetime(df["ts"].astype(int), unit="ms")
76
- df = df.sort_values("ts").reset_index(drop=True)
77
- return df
78
  except Exception as e:
79
- print(f"OKX candles attempt {attempt+1} failed: {e}")
80
  if attempt < 2:
81
  time.sleep(2)
82
  return None
@@ -91,20 +90,19 @@ def compute_rsi(series, period=14):
91
  rs = gain / loss
92
  return 100 - (100 / (1 + rs))
93
 
94
- def train_models_from_okx():
95
- """OKX'ten çekilen mum verisiyle XGBoost ve KNN modellerini eğitir."""
96
- df = fetch_okx_candles(limit=500)
97
  if df is None or len(df) < 50:
98
  return None, None, None, None
99
 
100
- # Teknik göstergeler
101
  df["ma_5"] = df["close"].rolling(5).mean()
102
  df["ma_20"] = df["close"].rolling(20).mean()
103
  df["rsi"] = compute_rsi(df["close"], 14)
104
  df["macd"] = df["close"].ewm(span=12).mean() - df["close"].ewm(span=26).mean()
105
  df["target"] = (df["close"].shift(-1) > df["close"]).astype(int)
106
-
107
  df_model = df.dropna().reset_index(drop=True)
 
108
  if len(df_model) < 20:
109
  return None, None, None, None
110
 
@@ -112,14 +110,12 @@ def train_models_from_okx():
112
  X = df_model[features].values
113
  y = df_model["target"].values
114
 
115
- # XGBoost
116
  xgb_model = xgb.XGBClassifier(
117
  n_estimators=50, max_depth=3, learning_rate=0.1,
118
  objective="binary:logistic", eval_metric="logloss", random_state=42
119
  )
120
  xgb_model.fit(X, y)
121
 
122
- # KNN (ölçeklendirme gerekli)
123
  scaler = StandardScaler()
124
  X_scaled = scaler.fit_transform(X)
125
  knn_model = KNeighborsClassifier(n_neighbors=5)
@@ -127,56 +123,47 @@ def train_models_from_okx():
127
 
128
  return xgb_model, knn_model, scaler, features
129
 
130
- # Başlangıçta modelleri OKX verisiyle eğit
131
- xgb_model, knn_model, scaler, feature_cols = train_models_from_okx()
132
 
133
  if xgb_model is None:
134
- # OKX erişilemezse fallback: basit dummy modeller
135
- print("OKX erişilemedi, dummy modeller kullanılıyor.")
136
  dummy_X = np.random.rand(50, 5)
137
  dummy_y = np.random.randint(0, 2, 50)
138
  xgb_model = xgb.XGBClassifier(n_estimators=10, max_depth=2)
139
  xgb_model.fit(dummy_X, dummy_y)
140
  scaler = StandardScaler()
141
- dummy_X_scaled = scaler.fit_transform(dummy_X)
142
  knn_model = KNeighborsClassifier(n_neighbors=5)
143
- knn_model.fit(dummy_X_scaled, dummy_y)
144
- feature_cols = ["ma_5", "ma_20", "rsi", "macd", "vol"]
145
 
146
  # ==========================================
147
  # 🧠 4. ANALİZ MOTORU (XGB + KNN Ensemble)
148
  # ==========================================
149
  def predict_and_analyze():
150
- # 1) OKX'ten canlı veri çek
151
- ticker = fetch_okx_ticker()
152
- candles = fetch_okx_candles(limit=30)
153
 
154
  if ticker is None or candles is None:
155
- return "❌ OKX API'sine erişilemedi. Cloudflare engellemesi olabilir. Lütfen daha sonra tekrar deneyin.", {}
156
 
157
  last_price = ticker["last"]
158
  change_pct = ticker["change_pct"]
159
  vol24h = ticker["vol24h"]
160
 
161
- # 2) Teknik göstergeler
162
  close = candles["close"]
163
  ma5 = close.rolling(5).mean().iloc[-1]
164
  ma20 = close.rolling(20).mean().iloc[-1]
165
  rsi = compute_rsi(close, 14).iloc[-1]
166
  macd = (close.ewm(span=12).mean() - close.ewm(span=26).mean()).iloc[-1]
167
 
168
- # 3) XGBoost ve KNN tahminleri
169
  feat_arr = np.array([[ma5, ma20, rsi, macd, vol24h]])
170
 
171
  xgb_prob_up = float(xgb_model.predict_proba(feat_arr)[0][1])
 
172
 
173
- feat_scaled = scaler.transform(feat_arr)
174
- knn_prob_up = float(knn_model.predict_proba(feat_scaled)[0][1])
175
-
176
- # 4) Ensemble (ortalama)
177
  ensemble_prob_up = (xgb_prob_up + knn_prob_up) / 2
178
  ensemble_prob_down = 1 - ensemble_prob_up
179
-
180
  direction = "YUKARI 📈" if ensemble_prob_up > 0.5 else "AŞAĞI 📉"
181
  confidence = max(ensemble_prob_up, ensemble_prob_down) * 100
182
 
@@ -189,7 +176,7 @@ def predict_and_analyze():
189
  prompt = f"""
190
  Sen uzman bir kripto para analisti ve teknik analiz uzmanısın.
191
 
192
- 📡 OKX Canlı Verileri (BTC/USDT):
193
  - Son Fiyat: ${last_price:,.2f}
194
  - 24s Değişim: %{change_pct:+.2f}
195
  - 24s Hacim: {vol24h:,.0f} BTC
@@ -201,17 +188,17 @@ def predict_and_analyze():
201
  - MACD: {macd:.4f}
202
 
203
  🤖 Model Sonuçları:
204
- - XGBoost Yükseliş Olasılığı: %{xgb_prob_up*100:.1f}
205
- - KNN Yükseliş Olasılığı: %{knn_prob_up*100:.1f}
206
- - Ensemble (Ortalama) Yükseliş Olasılığı: %{ensemble_prob_up*100:.1f}
207
  - Tahmin Yönü: {direction} (Güven: %{confidence:.1f})
208
 
209
- Türkçe bir teknik analiz raporu hazırla. Şu başlıklar bulunsun:
210
- 1. 🎯 Model Yorumu (XGBoost ve KNN'in karşılaştırmalı mantığı)
211
  2. 📈 Teknik Analiz (RSI, MA, MACD; destek/direnç)
212
- 3. 💡 İşlem Stratejisi (Long/Short, stop-loss, take-profit, risk yönetimi)
213
 
214
- Yatırım tavsiyesi olmadığını vurgula. Rasyonel ve profesyonel ol.
215
  """
216
 
217
  if client:
@@ -229,7 +216,7 @@ def predict_and_analyze():
229
  analysis_result = "GROQ_API_KEY bulunamadı! Hugging Face Secrets'a ekleyin."
230
 
231
  header = (
232
- f"**OKX Canlı: ${last_price:,.2f}** (%{change_pct:+.2f}) | RSI: {rsi:.1f} | "
233
  f"MA5: ${ma5:,.0f} | MA20: ${ma20:,.0f}\n\n"
234
  f"**XGB:** %{xgb_prob_up*100:.1f} | **KNN:** %{knn_prob_up*100:.1f} | "
235
  f"**Ensemble:** %{ensemble_prob_up*100:.1f}\n\n---\n\n"
@@ -242,36 +229,19 @@ def predict_and_analyze():
242
  with gr.Blocks(theme=gr.themes.Soft(primary_hue="orange", secondary_hue="slate")) as demo:
243
  gr.Markdown(
244
  """
245
- # ₿ BTC/USD XGBoost + KNN & Groq AI Tahmin Radarı (OKX Canlı)
246
- Fiyat ve mum verileri **OKX halka açık API**'sinden otomatik çekilir. **XGBoost + KNN** ensemble tahmini yapar, **Groq** analiz raporu üretir.
247
  """
248
  )
249
-
250
  with gr.Row():
251
  with gr.Column():
252
- analyze_btn = gr.Button("🔄 OKX'ten Veri Çek ve Analiz Et", variant="primary", size="lg")
253
- gr.Markdown(
254
- """
255
- **Not**: OKX API'si Cloudflare koruması altındadır. Kod, tarayıcı benzeri User-Agent ve 3 deneme mekanizması içerir.
256
- """
257
- )
258
-
259
  with gr.Column():
260
  prob_output = gr.Label(label="Model Tahminleri (XGB + KNN)")
261
- analysis_output = gr.Markdown(value="Butona basarak OKX'ten canlı veri çekip analizi başlatın.")
262
-
263
- analyze_btn.click(
264
- fn=predict_and_analyze,
265
- inputs=[],
266
- outputs=[analysis_output, prob_output]
267
- )
268
-
269
- gr.Markdown(
270
- """
271
- ---
272
- ⚠️ **Yatırım Tavsiyesi Değildir**: Bu uygulama eğitim amaçlıdır.
273
- """
274
- )
275
 
276
  if __name__ == "__main__":
277
  demo.launch()
 
18
  client = Groq(api_key=api_key)
19
 
20
  # ==========================================
21
+ # 📡 2. MEXC PUBLIC API
22
  # ==========================================
23
+ MEXC_BASE = "https://api.mexc.com"
24
 
25
+ # Akamai WAF'ın Python varsayılan UA'sını engellemesini aşmak için
26
+ MEXC_HEADERS = {
27
  "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
28
  "(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
29
  "Accept": "application/json",
30
  "Accept-Language": "en-US,en;q=0.9",
31
  }
32
 
33
+ def fetch_mexc_ticker(symbol="BTCUSDT"):
34
+ """MEXC spot son fiyat. 3 kez dener."""
35
  for attempt in range(3):
36
  try:
37
  r = requests.get(
38
+ f"{MEXC_BASE}/api/v3/ticker/24hr",
39
+ params={"symbol": symbol},
40
+ headers=MEXC_HEADERS,
41
  timeout=15
42
  )
43
  r.raise_for_status()
44
+ d = r.json()
45
  return {
46
+ "last": float(d["lastPrice"]),
47
+ "open24h": float(d["openPrice"]),
48
+ "high24h": float(d["highPrice"]),
49
+ "low24h": float(d["lowPrice"]),
50
+ "vol24h": float(d["volume"]),
51
+ "change_pct": float(d["priceChangePercent"]),
52
  }
53
  except Exception as e:
54
+ print(f"MEXC ticker attempt {attempt+1} failed: {e}")
55
  if attempt < 2:
56
  time.sleep(2)
57
  return None
58
 
59
+ def fetch_mexc_klines(symbol="BTCUSDT", interval="1h", limit=100):
60
+ """MEXC spot K-line. 3 kez dener."""
61
  for attempt in range(3):
62
  try:
63
  r = requests.get(
64
+ f"{MEXC_BASE}/api/v3/klines",
65
+ params={"symbol": symbol, "interval": interval, "limit": limit},
66
+ headers=MEXC_HEADERS,
67
  timeout=15
68
  )
69
  r.raise_for_status()
70
+ raw = r.json()
71
+ cols = ["ts","open","high","low","close","vol","close_time","qvol","trades","tb","tq","ignore"]
72
+ df = pd.DataFrame(raw, columns=cols)
73
+ for c in ["open","high","low","close","vol"]:
74
+ df[c] = df[c].astype(float)
75
  df["ts"] = pd.to_datetime(df["ts"].astype(int), unit="ms")
76
+ return df[["ts","open","high","low","close","vol"]].sort_values("ts").reset_index(drop=True)
 
77
  except Exception as e:
78
+ print(f"MEXC klines attempt {attempt+1} failed: {e}")
79
  if attempt < 2:
80
  time.sleep(2)
81
  return None
 
90
  rs = gain / loss
91
  return 100 - (100 / (1 + rs))
92
 
93
+ def train_models_from_mexc():
94
+ """MEXC'ten çekilen mum verisiyle XGBoost ve KNN eğitir."""
95
+ df = fetch_mexc_klines(limit=500)
96
  if df is None or len(df) < 50:
97
  return None, None, None, None
98
 
 
99
  df["ma_5"] = df["close"].rolling(5).mean()
100
  df["ma_20"] = df["close"].rolling(20).mean()
101
  df["rsi"] = compute_rsi(df["close"], 14)
102
  df["macd"] = df["close"].ewm(span=12).mean() - df["close"].ewm(span=26).mean()
103
  df["target"] = (df["close"].shift(-1) > df["close"]).astype(int)
 
104
  df_model = df.dropna().reset_index(drop=True)
105
+
106
  if len(df_model) < 20:
107
  return None, None, None, None
108
 
 
110
  X = df_model[features].values
111
  y = df_model["target"].values
112
 
 
113
  xgb_model = xgb.XGBClassifier(
114
  n_estimators=50, max_depth=3, learning_rate=0.1,
115
  objective="binary:logistic", eval_metric="logloss", random_state=42
116
  )
117
  xgb_model.fit(X, y)
118
 
 
119
  scaler = StandardScaler()
120
  X_scaled = scaler.fit_transform(X)
121
  knn_model = KNeighborsClassifier(n_neighbors=5)
 
123
 
124
  return xgb_model, knn_model, scaler, features
125
 
126
+ # Başlangıçta modelleri MEXC verisiyle eğit
127
+ xgb_model, knn_model, scaler, feature_cols = train_models_from_mexc()
128
 
129
  if xgb_model is None:
130
+ print("MEXC erişilemedi, dummy modeller kullanılıyor.")
 
131
  dummy_X = np.random.rand(50, 5)
132
  dummy_y = np.random.randint(0, 2, 50)
133
  xgb_model = xgb.XGBClassifier(n_estimators=10, max_depth=2)
134
  xgb_model.fit(dummy_X, dummy_y)
135
  scaler = StandardScaler()
 
136
  knn_model = KNeighborsClassifier(n_neighbors=5)
137
+ knn_model.fit(scaler.fit_transform(dummy_X), dummy_y)
138
+ feature_cols = ["ma_5","ma_20","rsi","macd","vol"]
139
 
140
  # ==========================================
141
  # 🧠 4. ANALİZ MOTORU (XGB + KNN Ensemble)
142
  # ==========================================
143
  def predict_and_analyze():
144
+ ticker = fetch_mexc_ticker()
145
+ candles = fetch_mexc_klines(limit=30)
 
146
 
147
  if ticker is None or candles is None:
148
+ return "❌ MEXC API'sine erişilemedi (Akamai WAF veya Hugging Face ağ kısıtlaması). Lütfen sonra tekrar deneyin.", {}
149
 
150
  last_price = ticker["last"]
151
  change_pct = ticker["change_pct"]
152
  vol24h = ticker["vol24h"]
153
 
 
154
  close = candles["close"]
155
  ma5 = close.rolling(5).mean().iloc[-1]
156
  ma20 = close.rolling(20).mean().iloc[-1]
157
  rsi = compute_rsi(close, 14).iloc[-1]
158
  macd = (close.ewm(span=12).mean() - close.ewm(span=26).mean()).iloc[-1]
159
 
 
160
  feat_arr = np.array([[ma5, ma20, rsi, macd, vol24h]])
161
 
162
  xgb_prob_up = float(xgb_model.predict_proba(feat_arr)[0][1])
163
+ knn_prob_up = float(knn_model.predict_proba(scaler.transform(feat_arr))[0][1])
164
 
 
 
 
 
165
  ensemble_prob_up = (xgb_prob_up + knn_prob_up) / 2
166
  ensemble_prob_down = 1 - ensemble_prob_up
 
167
  direction = "YUKARI 📈" if ensemble_prob_up > 0.5 else "AŞAĞI 📉"
168
  confidence = max(ensemble_prob_up, ensemble_prob_down) * 100
169
 
 
176
  prompt = f"""
177
  Sen uzman bir kripto para analisti ve teknik analiz uzmanısın.
178
 
179
+ 📡 MEXC Canlı Verileri (BTC/USDT):
180
  - Son Fiyat: ${last_price:,.2f}
181
  - 24s Değişim: %{change_pct:+.2f}
182
  - 24s Hacim: {vol24h:,.0f} BTC
 
188
  - MACD: {macd:.4f}
189
 
190
  🤖 Model Sonuçları:
191
+ - XGBoost Yükseliş: %{xgb_prob_up*100:.1f}
192
+ - KNN Yükseliş: %{knn_prob_up*100:.1f}
193
+ - Ensemble Yükseliş: %{ensemble_prob_up*100:.1f}
194
  - Tahmin Yönü: {direction} (Güven: %{confidence:.1f})
195
 
196
+ Türkçe bir teknik analiz raporu hazırla. Başlıklar:
197
+ 1. 🎯 Model Yorumu (XGBoost + KNN karşılaştırması)
198
  2. 📈 Teknik Analiz (RSI, MA, MACD; destek/direnç)
199
+ 3. 💡 İşlem Stratejisi (Long/Short, stop-loss, take-profit)
200
 
201
+ Yatırım tavsiyesi olmadığını vurgula.
202
  """
203
 
204
  if client:
 
216
  analysis_result = "GROQ_API_KEY bulunamadı! Hugging Face Secrets'a ekleyin."
217
 
218
  header = (
219
+ f"**MEXC Canlı: ${last_price:,.2f}** (%{change_pct:+.2f}) | RSI: {rsi:.1f} | "
220
  f"MA5: ${ma5:,.0f} | MA20: ${ma20:,.0f}\n\n"
221
  f"**XGB:** %{xgb_prob_up*100:.1f} | **KNN:** %{knn_prob_up*100:.1f} | "
222
  f"**Ensemble:** %{ensemble_prob_up*100:.1f}\n\n---\n\n"
 
229
  with gr.Blocks(theme=gr.themes.Soft(primary_hue="orange", secondary_hue="slate")) as demo:
230
  gr.Markdown(
231
  """
232
+ # ₿ BTC/USD XGBoost + KNN & Groq AI Tahmin Radarı (MEXC Canlı)
233
+ Fiyat ve mum verileri **MEXC halka açık API**'sinden otomatik çekilir. **XGBoost + KNN** ensemble tahmini yapar, **Groq** analiz raporu üretir.
234
  """
235
  )
 
236
  with gr.Row():
237
  with gr.Column():
238
+ analyze_btn = gr.Button("🔄 MEXC'ten Veri Çek ve Analiz Et", variant="primary", size="lg")
239
+ gr.Markdown("**Not**: MEXC API'si Akamai WAF koruması altındadır; kod tarayıcı UA ve 3 deneme içerir.")
 
 
 
 
 
240
  with gr.Column():
241
  prob_output = gr.Label(label="Model Tahminleri (XGB + KNN)")
242
+ analysis_output = gr.Markdown(value="Butona basarak MEXC'ten canlı veri çekip analizi başlatın.")
243
+ analyze_btn.click(fn=predict_and_analyze, inputs=[], outputs=[analysis_output, prob_output])
244
+ gr.Markdown("---\n⚠️ **Yatırım Tavsiyesi Değildir**: Bu uygulama eğitim amaçlıdır.")
 
 
 
 
 
 
 
 
 
 
 
245
 
246
  if __name__ == "__main__":
247
  demo.launch()