GoshawkVortexAI commited on
Commit
9730b8e
·
verified ·
1 Parent(s): deea9c4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -193
app.py CHANGED
@@ -1,8 +1,5 @@
1
  import os
2
- import time
3
- import requests
4
  import numpy as np
5
- import pandas as pd
6
  import gradio as gr
7
  import xgboost as xgb
8
  from groq import Groq
@@ -16,191 +13,44 @@ if api_key:
16
  client = Groq(api_key=api_key)
17
 
18
  # ==========================================
19
- # 📡 2. API İSTEK BAŞLIKLARI (Cloudflare engelini aşmak için)
20
  # ==========================================
21
- HEADERS = {
22
- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
23
- "(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
24
- "Accept": "application/json",
25
- "Accept-Language": "en-US,en;q=0.9",
26
- }
 
 
 
 
 
 
 
 
27
 
28
- OKX_BASE = "https://www.okx.com/api/v5"
29
- BINANCE_BASE = "https://api.binance.com/api/v3"
30
-
31
- # ==========================================
32
- # 📡 3. VERİ ÇEKME FONKSİYONLARI (Retry + Fallback)
33
- # ==========================================
34
- def fetch_okx_ticker(inst_id="BTC-USDT"):
35
- """OKX'ten anlık fiyat çeker. 3 kez dener."""
36
- for attempt in range(3):
37
- try:
38
- r = requests.get(f"{OKX_BASE}/market/ticker",
39
- params={"instId": inst_id},
40
- headers=HEADERS, timeout=15)
41
- r.raise_for_status()
42
- d = r.json()["data"][0]
43
- return {
44
- "source": "OKX",
45
- "last": float(d["last"]),
46
- "open24h": float(d["open24h"]),
47
- "high24h": float(d["high24h"]),
48
- "low24h": float(d["low24h"]),
49
- "vol24h": float(d["vol24h"]),
50
- "change_pct": (float(d["last"]) / float(d["open24h"]) - 1) * 100
51
- }
52
- except Exception as e:
53
- print(f"OKX ticker attempt {attempt+1} failed: {e}")
54
- if attempt < 2:
55
- time.sleep(2)
56
- return None
57
-
58
-
59
- def fetch_binance_ticker(symbol="BTCUSDT"):
60
- """OKX başarısız olursa Binance'ten fiyat çeker (yedek)."""
61
- try:
62
- r = requests.get(f"{BINANCE_BASE}/ticker/24hr",
63
- params={"symbol": symbol},
64
- headers=HEADERS, timeout=15)
65
- r.raise_for_status()
66
- d = r.json()
67
- return {
68
- "source": "Binance",
69
- "last": float(d["lastPrice"]),
70
- "open24h": float(d["openPrice"]),
71
- "high24h": float(d["highPrice"]),
72
- "low24h": float(d["lowPrice"]),
73
- "vol24h": float(d["volume"]),
74
- "change_pct": float(d["priceChangePercent"])
75
- }
76
- except Exception as e:
77
- print(f"Binance ticker failed: {e}")
78
- return None
79
-
80
-
81
- def fetch_okx_candles(inst_id="BTC-USDT", bar="1H", limit=100):
82
- """OKX'ten mum verisi çeker."""
83
- for attempt in range(3):
84
- try:
85
- r = requests.get(f"{OKX_BASE}/market/candles",
86
- params={"instId": inst_id, "bar": bar, "limit": limit},
87
- headers=HEADERS, timeout=15)
88
- r.raise_for_status()
89
- raw = r.json()["data"]
90
- df = pd.DataFrame(raw, columns=["ts", "open", "high", "low", "close", "vol"])
91
- for col in ["open", "high", "low", "close", "vol"]:
92
- df[col] = df[col].astype(float)
93
- df["ts"] = pd.to_datetime(df["ts"].astype(int), unit="ms")
94
- df = df.sort_values("ts").reset_index(drop=True)
95
- return df
96
- except Exception as e:
97
- print(f"OKX candles attempt {attempt+1} failed: {e}")
98
- if attempt < 2:
99
- time.sleep(2)
100
- return None
101
-
102
-
103
- def fetch_binance_candles(symbol="BTCUSDT", interval="1h", limit=100):
104
- """OKX başarısız olursa Binance'ten mum verisi çeker."""
105
- try:
106
- r = requests.get(f"{BINANCE_BASE}/klines",
107
- params={"symbol": symbol, "interval": interval, "limit": limit},
108
- headers=HEADERS, timeout=15)
109
- r.raise_for_status()
110
- raw = r.json()
111
- df = pd.DataFrame(raw, columns=[
112
- "ts", "open", "high", "low", "close", "vol",
113
- "close_time", "quote_vol", "trades", "buy_base", "buy_quote", "ignore"
114
- ])
115
- for col in ["open", "high", "low", "close", "vol"]:
116
- df[col] = df[col].astype(float)
117
- df["ts"] = pd.to_datetime(df["ts"].astype(int), unit="ms")
118
- return df[["ts", "open", "high", "low", "close", "vol"]]
119
- except Exception as e:
120
- print(f"Binance candles failed: {e}")
121
- return None
122
-
123
-
124
- def fetch_market_data():
125
- """Önce OKX'i dener, başarısız olursa Binance'e geçer."""
126
- ticker = fetch_okx_ticker()
127
- candles = fetch_okx_candles()
128
-
129
- if ticker is not None and candles is not None:
130
- return ticker, candles
131
-
132
- print("OKX failed, switching to Binance fallback...")
133
- ticker = fetch_binance_ticker()
134
- candles = fetch_binance_candles()
135
- return ticker, candles
136
-
137
-
138
- def compute_rsi(series, period=14):
139
- delta = series.diff()
140
- gain = delta.clip(lower=0).rolling(period).mean()
141
- loss = -delta.clip(upper=0).rolling(period).mean()
142
- rs = gain / loss
143
- return 100 - (100 / (1 + rs))
144
-
145
- # ==========================================
146
- # 🤖 4. XGBOOST MODEL EĞİTİMİ
147
- # ==========================================
148
- def train_model():
149
- """Çekilen mum verisiyle XGBoost modelini eğitir."""
150
- df = fetch_okx_candles(limit=500)
151
- if df is None:
152
- df = fetch_binance_candles(limit=500)
153
-
154
- if df is None or len(df) < 50:
155
- return None
156
-
157
- df["ma_5"] = df["close"].rolling(5).mean()
158
- df["ma_20"] = df["close"].rolling(20).mean()
159
- df["rsi"] = compute_rsi(df["close"], 14)
160
- df["macd"] = df["close"].ewm(span=12).mean() - df["close"].ewm(span=26).mean()
161
- df["target"] = (df["close"].shift(-1) > df["close"]).astype(int)
162
- df = df.dropna().reset_index(drop=True)
163
-
164
- features = ["ma_5", "ma_20", "rsi", "macd", "vol"]
165
  model = xgb.XGBClassifier(
166
  n_estimators=50, max_depth=3, learning_rate=0.1,
167
  objective="binary:logistic", eval_metric="logloss", random_state=42
168
  )
169
- model.fit(df[features], df["target"])
170
  return model
171
 
172
-
173
- # Uygulama başlarken modeli eğit
174
- xgb_model = train_model()
175
- if xgb_model is None:
176
- # Fallback: API hiç çalışmazsa dummy model
177
- xgb_model = xgb.XGBClassifier(n_estimators=10, max_depth=2)
178
- xgb_model.fit(np.random.rand(20, 5), np.random.randint(0, 2, 20))
179
 
180
  # ==========================================
181
- # 🧠 5. ANALİZ MOTORU
182
  # ==========================================
183
- def predict_and_analyze():
184
- ticker, candles = fetch_market_data()
185
-
186
- if ticker is None or candles is None:
187
- return "❌ Hem OKX hem de Binance API'sine erişilemedi. Lütfen daha sonra tekrar deneyin.", {}
188
-
189
- last_price = ticker["last"]
190
- change_pct = ticker["change_pct"]
191
- vol24h = ticker["vol24h"]
192
- source = ticker["source"]
193
-
194
- close = candles["close"]
195
- ma5 = close.rolling(5).mean().iloc[-1]
196
- ma20 = close.rolling(20).mean().iloc[-1]
197
- rsi = compute_rsi(close, 14).iloc[-1]
198
- macd = (close.ewm(span=12).mean() - close.ewm(span=26).mean()).iloc[-1]
199
 
200
  # XGBoost tahmini
201
- features = np.array([[ma5, ma20, rsi, macd, vol24h]])
202
  prob_up = float(xgb_model.predict_proba(features)[0][1])
203
  prob_down = 1 - prob_up
 
204
  direction = "YUKARI 📈" if prob_up > 0.5 else "AŞAĞI 📉"
205
  confidence = max(prob_up, prob_down) * 100
206
 
@@ -212,16 +62,12 @@ def predict_and_analyze():
212
  prompt = f"""
213
  Sen uzman bir kripto para analisti ve teknik analiz uzmanısın.
214
 
215
- 📡 Canlı Veri Kaynağı: {source} (BTC/USDT)
216
  - Son Fiyat: ${last_price:,.2f}
217
- - 24s Değişim: %{change_pct:+.2f}
218
- - 24s Hacim: {vol24h:,.0f} BTC
219
- - 24s Yüksek/Düşük: ${ticker['high24h']:,.2f} / ${ticker['low24h']:,.2f}
220
-
221
- 📊 Teknik Göstergeler (1H):
222
  - RSI (14): {rsi:.2f}
223
  - MA5: ${ma5:,.2f} | MA20: ${ma20:,.2f}
224
  - MACD: {macd:.4f}
 
225
 
226
  🤖 XGBoost Model Sonucu:
227
  - Yükseliş Olasılığı: %{prob_up*100:.1f}
@@ -230,7 +76,7 @@ def predict_and_analyze():
230
 
231
  Türkçe bir teknik analiz raporu hazırla. Şu başlıklar bulunsun:
232
  1. 🎯 Model Yorumu (XGBoost + teknik göstergelerin mantığı)
233
- 2. 📈 Teknik Analiz (RSI, MA, MACD; destek/direnç)
234
  3. 💡 İşlem Stratejisi (Long/Short, stop-loss, take-profit, risk yönetimi)
235
 
236
  Yatırım tavsiyesi olmadığını vurgula. Rasyonel ve profesyonel ol.
@@ -251,43 +97,54 @@ def predict_and_analyze():
251
  analysis_result = "GROQ_API_KEY bulunamadı! Hugging Face Secrets'a ekleyin."
252
 
253
  header = (
254
- f"**Kaynak: {source}** | **Canlı: ${last_price:,.2f}** (%{change_pct:+.2f}) | "
255
  f"RSI: {rsi:.1f} | MA5: ${ma5:,.0f} | MA20: ${ma20:,.0f}\n\n---\n\n"
256
  )
257
  return header + analysis_result, prob_dict
258
 
259
  # ==========================================
260
- # 🎨 6. GRADIO ARAYÜZÜ
261
  # ==========================================
262
  with gr.Blocks(theme=gr.themes.Soft(primary_hue="orange", secondary_hue="slate")) as demo:
263
  gr.Markdown(
264
  """
265
- # ₿ BTC/USD XGBoost & Groq AI Tahmin Radarı (Canlı)
266
- Veriler **OKX halka açık API**'sinden çekilir; OKX'e erişilemezse otomatik olarak **Binance**'e geçilir. **XGBoost** yön tahmini yapar, **Groq** analiz raporu üretir.
267
  """
268
  )
269
 
270
  with gr.Row():
271
  with gr.Column():
272
- analyze_btn = gr.Button("🔄 Canlı Veri Çek ve Analiz Et", variant="primary", size="lg")
273
- gr.Markdown(
274
- "**Not**: API rate limit nedeniyle butona çok hızlı basmayın."
275
- )
 
 
 
 
 
 
 
 
276
 
277
  with gr.Column():
278
- prob_output = gr.Label(label="XGBoost Yön Tahmini")
279
- analysis_output = gr.Markdown(value="Butona basarak canlı veri çekip analizi başlatın.")
 
 
 
280
 
281
- analyze_btn.click(
282
  fn=predict_and_analyze,
283
- inputs=[],
284
  outputs=[analysis_output, prob_output]
285
  )
286
 
287
  gr.Markdown(
288
  """
289
  ---
290
- ⚠️ **Yatırım Tavsiyesi Değildir**: Bu uygulama eğitim amaçlıdır. Kripto paralar yüksek risk içerir.
291
  """
292
  )
293
 
 
1
  import os
 
 
2
  import numpy as np
 
3
  import gradio as gr
4
  import xgboost as xgb
5
  from groq import Groq
 
13
  client = Groq(api_key=api_key)
14
 
15
  # ==========================================
16
+ # 🤖 2. XGBOOST MODEL EĞİTİMİ (Sanal Veri)
17
  # ==========================================
18
+ def train_dummy_model():
19
+ """API olmadan çalışabilmesi için sanal veriyle hızlı eğitim."""
20
+ np.random.seed(42)
21
+ n = 300
22
+ # Sanal BTC verisi (gerçekçi aralıkta)
23
+ ma5 = np.random.uniform(55000, 75000, n)
24
+ ma20 = ma5 + np.random.normal(0, 500, n)
25
+ rsi = np.random.uniform(20, 80, n)
26
+ macd = np.random.normal(0, 200, n)
27
+ vol = np.random.uniform(100, 1000, n)
28
+
29
+ X = np.column_stack([ma5, ma20, rsi, macd, vol])
30
+ # Hedef: MA5 > MA20 ve RSI < 70 ise yukarı eğilim (sanal mantık)
31
+ y = ((ma5 > ma20) & (rsi < 70)).astype(int)
32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  model = xgb.XGBClassifier(
34
  n_estimators=50, max_depth=3, learning_rate=0.1,
35
  objective="binary:logistic", eval_metric="logloss", random_state=42
36
  )
37
+ model.fit(X, y)
38
  return model
39
 
40
+ xgb_model = train_dummy_model()
 
 
 
 
 
 
41
 
42
  # ==========================================
43
+ # 🧠 3. ANALİZ MOTORU (Manuel Giriş)
44
  # ==========================================
45
+ def predict_and_analyze(last_price, rsi, ma5, ma20, macd, vol):
46
+ if not last_price or last_price <= 0:
47
+ return "Lütfen geçerli bir BTC/USD fiyatı giriniz.", {}
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
  # XGBoost tahmini
50
+ features = np.array([[ma5, ma20, rsi, macd, vol]])
51
  prob_up = float(xgb_model.predict_proba(features)[0][1])
52
  prob_down = 1 - prob_up
53
+
54
  direction = "YUKARI 📈" if prob_up > 0.5 else "AŞAĞI 📉"
55
  confidence = max(prob_up, prob_down) * 100
56
 
 
62
  prompt = f"""
63
  Sen uzman bir kripto para analisti ve teknik analiz uzmanısın.
64
 
65
+ 📊 BTC/USD Piyasa Verileri (Manuel Giriş):
66
  - Son Fiyat: ${last_price:,.2f}
 
 
 
 
 
67
  - RSI (14): {rsi:.2f}
68
  - MA5: ${ma5:,.2f} | MA20: ${ma20:,.2f}
69
  - MACD: {macd:.4f}
70
+ - Hacim: {vol:,.2f}
71
 
72
  🤖 XGBoost Model Sonucu:
73
  - Yükseliş Olasılığı: %{prob_up*100:.1f}
 
76
 
77
  Türkçe bir teknik analiz raporu hazırla. Şu başlıklar bulunsun:
78
  1. 🎯 Model Yorumu (XGBoost + teknik göstergelerin mantığı)
79
+ 2. 📈 Teknik Analiz (RSI, MA, MACD; destek/direnç seviyeleri)
80
  3. 💡 İşlem Stratejisi (Long/Short, stop-loss, take-profit, risk yönetimi)
81
 
82
  Yatırım tavsiyesi olmadığını vurgula. Rasyonel ve profesyonel ol.
 
97
  analysis_result = "GROQ_API_KEY bulunamadı! Hugging Face Secrets'a ekleyin."
98
 
99
  header = (
100
+ f"**Manuel Veri** | **Fiyat: ${last_price:,.2f}** | "
101
  f"RSI: {rsi:.1f} | MA5: ${ma5:,.0f} | MA20: ${ma20:,.0f}\n\n---\n\n"
102
  )
103
  return header + analysis_result, prob_dict
104
 
105
  # ==========================================
106
+ # 🎨 4. GRADIO ARAYÜZÜ
107
  # ==========================================
108
  with gr.Blocks(theme=gr.themes.Soft(primary_hue="orange", secondary_hue="slate")) as demo:
109
  gr.Markdown(
110
  """
111
+ # ₿ BTC/USD XGBoost & Groq AI Tahmin Radarı (Manuel Giriş)
112
+ API erişim sorunları nedeniyle verileri **manuel** giriyorsunuz. **XGBoost** yön tahmini yapar, **Groq** analiz raporu üretir.
113
  """
114
  )
115
 
116
  with gr.Row():
117
  with gr.Column():
118
+ gr.Markdown("### 📊 Piyasa Verileri")
119
+ price_input = gr.Number(label="Güncel BTC/USD Fiyatı ($)", value=65000.0)
120
+ vol_input = gr.Number(label="24s Hacim (BTC)", value=500.0)
121
+
122
+ gr.Markdown("### 📈 Teknik Göstergeler")
123
+ rsi_input = gr.Slider(label="RSI (14)", minimum=0, maximum=100, value=55.0, step=0.1)
124
+ with gr.Row():
125
+ ma5_input = gr.Number(label="MA5 ($)", value=64800.0)
126
+ ma20_input = gr.Number(label="MA20 ($)", value=64000.0)
127
+ macd_input = gr.Number(label="MACD Değeri", value=150.0)
128
+
129
+ submit_btn = gr.Button("Analiz Et ve Tahmin Üret", variant="primary")
130
 
131
  with gr.Column():
132
+ gr.Markdown("### 📈 XGBoost Yön Tahmini")
133
+ prob_output = gr.Label(label="Olasılık Dağılımı")
134
+
135
+ gr.Markdown("### 🧠 Groq Yapay Zeka Analiz Raporu")
136
+ analysis_output = gr.Markdown(value="Verileri girdikten sonra butona basarak analizi başlatabilirsiniz.")
137
 
138
+ submit_btn.click(
139
  fn=predict_and_analyze,
140
+ inputs=[price_input, rsi_input, ma5_input, ma20_input, macd_input, vol_input],
141
  outputs=[analysis_output, prob_output]
142
  )
143
 
144
  gr.Markdown(
145
  """
146
  ---
147
+ ⚠️ **Yatırım Tavsiyesi Değildir**: Bu uygulama eğitim amaçlıdır.
148
  """
149
  )
150