GoshawkVortexAI commited on
Commit
7b7258e
·
verified ·
1 Parent(s): 3b00eec

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +126 -78
app.py CHANGED
@@ -1,4 +1,5 @@
1
  import os
 
2
  import numpy as np
3
  import pandas as pd
4
  import gradio as gr
@@ -6,7 +7,7 @@ import xgboost as xgb
6
  from groq import Groq
7
 
8
  # ==========================================
9
- # 🔌 1. GROQ CLIENT BAŞLATMA
10
  # ==========================================
11
  api_key = os.environ.get("GROQ_API_KEY")
12
  client = None
@@ -14,28 +15,47 @@ if api_key:
14
  client = Groq(api_key=api_key)
15
 
16
  # ==========================================
17
- # 📊 2. XGBOOST MODELİ İÇİN SANAL BTC VERİSİ
18
  # ==========================================
19
- def generate_btc_data(n=500, seed=42):
20
- """Demo amaçlı gerçekçi BTC/USD fiyat serisi üretir."""
21
- np.random.seed(seed)
22
- # Rastgele yürüyüş + hafif yukarı trend
23
- returns = np.random.normal(0.0005, 0.02, n)
24
- prices = 60000 * np.exp(np.cumsum(returns))
25
- volumes = np.random.uniform(100, 1000, n)
26
-
27
- df = pd.DataFrame({"close": prices, "volume": volumes})
28
-
29
- # Teknik göstergeler
30
- df["ma_5"] = df["close"].rolling(5).mean()
31
- df["ma_20"] = df["close"].rolling(20).mean()
32
- df["rsi"] = compute_rsi(df["close"], 14)
33
- df["macd"] = df["close"].ewm(span=12).mean() - df["close"].ewm(span=26).mean()
34
-
35
- # Hedef: Bir sonraki mumda fiyat artacak mı? (1 = yukarı, 0 = aşağı)
36
- df["target"] = (df["close"].shift(-1) > df["close"]).astype(int)
37
-
38
- return df.dropna().reset_index(drop=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
 
41
  def compute_rsi(series, period=14):
@@ -45,38 +65,69 @@ def compute_rsi(series, period=14):
45
  rs = gain / loss
46
  return 100 - (100 / (1 + rs))
47
 
 
48
  # ==========================================
49
- # 🤖 3. XGBOOST MODEL EĞİTİMİ
50
  # ==========================================
51
- def train_xgboost_model(df):
52
- features = ["ma_5", "ma_20", "rsi", "macd", "volume"]
 
 
 
 
 
 
 
 
 
 
 
 
53
  X = df[features]
54
  y = df["target"]
55
 
56
  model = xgb.XGBClassifier(
57
- n_estimators=50,
58
- max_depth=3,
59
- learning_rate=0.1,
60
- objective="binary:logistic",
61
- eval_metric="logloss",
62
- random_state=42
63
  )
64
  model.fit(X, y)
65
  return model, features
66
 
67
- # Başlangıçta veri üret ve modeli eğit
68
- btc_df = generate_btc_data()
69
- xgb_model, feature_cols = train_xgboost_model(btc_df)
 
 
 
 
 
 
 
70
 
71
  # ==========================================
72
- # 🧠 4. TAHMİN VE ANALİZ MOTORU
73
  # ==========================================
74
- def predict_and_analyze(current_price, rsi_value, ma5_value, ma20_value, macd_value, volume_value):
75
- if not current_price or current_price <= 0:
76
- return "Lütfen geçerli bir BTC/USD fiyatı giriniz.", {}
77
-
78
- # XGBoost girdisini hazırla
79
- features = np.array([[ma5_value, ma20_value, rsi_value, macd_value, volume_value]])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
  prob_up = float(xgb_model.predict_proba(features)[0][1])
81
  prob_down = 1 - prob_up
82
 
@@ -85,19 +136,23 @@ def predict_and_analyze(current_price, rsi_value, ma5_value, ma20_value, macd_va
85
  "Düşüş (Short) Olasılığı": prob_down,
86
  }
87
 
88
- # Yön tahmini
89
  direction = "YUKARI 📈" if prob_up > 0.5 else "AŞAĞI 📉"
90
  confidence = max(prob_up, prob_down) * 100
91
 
 
92
  prompt = f"""
93
  Sen uzman bir kripto para analisti ve teknik analiz uzmanısın.
94
 
95
- 📊 BTC/USD Piyasa Verileri:
96
- - Güncel Fiyat: ${current_price:.2f}
97
- - RSI (14): {rsi_value:.2f}
98
- - MA5: ${ma5_value:.2f} | MA20: ${ma20_value:.2f}
99
- - MACD: {macd_value:.4f}
100
- - Hacim: {volume_value:.2f}
 
 
 
 
101
 
102
  🤖 XGBoost Model Sonucu:
103
  - Yükseliş Olasılığı: %{prob_up*100:.1f}
@@ -105,11 +160,11 @@ def predict_and_analyze(current_price, rsi_value, ma5_value, ma20_value, macd_va
105
  - Tahmin Yönü: {direction} (Güven: %{confidence:.1f})
106
 
107
  Türkçe bir teknik analiz raporu hazırla. Şu başlıklar bulunsun:
108
- 1. 🎯 Model Yorumu (XGBoost olasılıklarının ve teknik göstergelerin mantığı)
109
- 2. 📈 Teknik Analiz (RSI, MA, MACD yorumu; destek/direnç seviyeleri)
110
- 3. 💡 İşlem Stratejisi (Long/Short önerisi, stop-loss, take-profit, risk yönetimi)
111
 
112
- Yorumların rasyonel, nesnel ve profesyonel olsun. Yatırım tavsiyesi olmadığını vurgula.
113
  """
114
 
115
  if client:
@@ -122,12 +177,14 @@ def predict_and_analyze(current_price, rsi_value, ma5_value, ma20_value, macd_va
122
  )
123
  analysis_result = response.choices[0].message.content
124
  except Exception as e:
125
- analysis_result = f"Groq API Analiz Hatası: {str(e)}\n\n(Lütfen GROQ_API_KEY değişkeninizi Hugging Face Secrets alanına doğru eklediğinizden emin olun.)"
126
  else:
127
- analysis_result = ("Groq API Anahtarı bulunamadı! Lütfen Hugging Face Space alanına "
128
- "'GROQ_API_KEY' adıyla bir Secret ekleyin. (Yine de yukarıdaki XGBoost tahminini görebilirsiniz.)")
 
 
 
129
 
130
- return analysis_result, prob_dict
131
 
132
  # ==========================================
133
  # 🎨 5. GRADIO ARAYÜZÜ
@@ -135,43 +192,34 @@ def predict_and_analyze(current_price, rsi_value, ma5_value, ma20_value, macd_va
135
  with gr.Blocks(theme=gr.themes.Soft(primary_hue="orange", secondary_hue="slate")) as demo:
136
  gr.Markdown(
137
  """
138
- # ₿ BTC/USD XGBoost & Groq AI Tahmin Radarı
139
- Bu uygulama, girdiğiniz piyasa verilerini **XGBoost** modeli ile analiz ederek yükseliş/düşüş olasılığını hesaplar; ardından **Groq (GPT-OSS)** yapay zekası ile teknik analiz raporu üretir.
140
  """
141
  )
142
 
143
  with gr.Row():
144
  with gr.Column():
145
- gr.Markdown("### 📊 Piyasa Verileri")
146
- price_input = gr.Number(label="Güncel BTC/USD Fiyatı ($)", value=65000.0)
147
- volume_input = gr.Number(label="24s Hacim (Milyon $)", value=500.0)
148
-
149
- gr.Markdown("### 📈 Teknik Göstergeler")
150
- rsi_input = gr.Slider(label="RSI (14)", minimum=0, maximum=100, value=55.0, step=0.1)
151
- with gr.Row():
152
- ma5_input = gr.Number(label="MA5 ($)", value=64800.0)
153
- ma20_input = gr.Number(label="MA20 ($)", value=64000.0)
154
- macd_input = gr.Number(label="MACD Değeri", value=150.0)
155
-
156
- submit_btn = gr.Button("Analiz Et ve Tahmin Üret", variant="primary")
157
 
158
  with gr.Column():
159
- gr.Markdown("### 📈 XGBoost Yön Tahmini")
160
- prob_output = gr.Label(label="Olasılık Dağılımı")
161
-
162
- gr.Markdown("### 🧠 Groq Yapay Zeka Analiz Raporu")
163
- analysis_output = gr.Markdown(value="Verileri girdikten sonra butona basarak analizi başlatabilirsiniz.")
164
 
165
- submit_btn.click(
166
  fn=predict_and_analyze,
167
- inputs=[price_input, rsi_input, ma5_input, ma20_input, macd_input, volume_input],
168
  outputs=[analysis_output, prob_output]
169
  )
170
 
171
  gr.Markdown(
172
  """
173
  ---
174
- ⚠️ **Yatırım Tavsiyesi Değildir**: Bu uygulama yalnızca eğitim ve analiz amaçlıdır. Kripto para piyasaları yüksek risk içerir; yatırım kararlarınızı kendi araştırmanıza dayandırın.
175
  """
176
  )
177
 
 
1
  import os
2
+ import requests
3
  import numpy as np
4
  import pandas as pd
5
  import gradio as gr
 
7
  from groq import Groq
8
 
9
  # ==========================================
10
+ # 🔌 1. GROQ CLIENT
11
  # ==========================================
12
  api_key = os.environ.get("GROQ_API_KEY")
13
  client = None
 
15
  client = Groq(api_key=api_key)
16
 
17
  # ==========================================
18
+ # 📡 2. OKX PUBLIC API VERİ ÇEKME
19
  # ==========================================
20
+ OKX_BASE = "https://www.okx.com/api/v5"
21
+
22
+ def fetch_okx_ticker(inst_id="BTC-USDT"):
23
+ """OKX'ten anlık fiyat ve 24s verileri çeker (API Key gerekmez)."""
24
+ try:
25
+ r = requests.get(f"{OKX_BASE}/market/ticker", params={"instId": inst_id}, timeout=10)
26
+ r.raise_for_status()
27
+ d = r.json()["data"][0]
28
+ return {
29
+ "last": float(d["last"]),
30
+ "open24h": float(d["open24h"]),
31
+ "high24h": float(d["high24h"]),
32
+ "low24h": float(d["low24h"]),
33
+ "vol24h": float(d["vol24h"]),
34
+ "change_pct": (float(d["last"]) / float(d["open24h"]) - 1) * 100
35
+ }
36
+ except Exception as e:
37
+ print(f"OKX ticker error: {e}")
38
+ return None
39
+
40
+
41
+ def fetch_okx_candles(inst_id="BTC-USDT", bar="1H", limit=100):
42
+ """OKX'ten mum verisi çeker ve DataFrame döndürür."""
43
+ try:
44
+ r = requests.get(f"{OKX_BASE}/market/candles",
45
+ params={"instId": inst_id, "bar": bar, "limit": limit},
46
+ timeout=10)
47
+ r.raise_for_status()
48
+ raw = r.json()["data"]
49
+ # OKX mum formatı: [ts, open, high, low, close, vol, ...]
50
+ df = pd.DataFrame(raw, columns=["ts", "open", "high", "low", "close", "vol"])
51
+ for col in ["open", "high", "low", "close", "vol"]:
52
+ df[col] = df[col].astype(float)
53
+ df["ts"] = pd.to_datetime(df["ts"].astype(int), unit="ms")
54
+ df = df.sort_values("ts").reset_index(drop=True)
55
+ return df
56
+ except Exception as e:
57
+ print(f"OKX candles error: {e}")
58
+ return None
59
 
60
 
61
  def compute_rsi(series, period=14):
 
65
  rs = gain / loss
66
  return 100 - (100 / (1 + rs))
67
 
68
+
69
  # ==========================================
70
+ # 🤖 3. XGBOOST MODEL EĞİTİMİ (OKX verisiyle)
71
  # ==========================================
72
+ def train_model_from_okx():
73
+ """OKX'ten çekilen mum verisiyle XGBoost modelini eğitir."""
74
+ df = fetch_okx_candles(bar="1H", limit=500)
75
+ if df is None or len(df) < 50:
76
+ return None, None
77
+
78
+ df["ma_5"] = df["close"].rolling(5).mean()
79
+ df["ma_20"] = df["close"].rolling(20).mean()
80
+ df["rsi"] = compute_rsi(df["close"], 14)
81
+ df["macd"] = df["close"].ewm(span=12).mean() - df["close"].ewm(span=26).mean()
82
+ df["target"] = (df["close"].shift(-1) > df["close"]).astype(int)
83
+
84
+ df = df.dropna().reset_index(drop=True)
85
+ features = ["ma_5", "ma_20", "rsi", "macd", "vol"]
86
  X = df[features]
87
  y = df["target"]
88
 
89
  model = xgb.XGBClassifier(
90
+ n_estimators=50, max_depth=3, learning_rate=0.1,
91
+ objective="binary:logistic", eval_metric="logloss", random_state=42
 
 
 
 
92
  )
93
  model.fit(X, y)
94
  return model, features
95
 
96
+
97
+ # Başlangıçta modeli OKX verisiyle eğit
98
+ xgb_model, feature_cols = train_model_from_okx()
99
+ if xgb_model is None:
100
+ # Fallback: OKX erişilemezse basit bir dummy model
101
+ xgb_model = xgb.XGBClassifier(n_estimators=10, max_depth=2)
102
+ dummy_X = np.random.rand(20, 5)
103
+ dummy_y = np.random.randint(0, 2, 20)
104
+ xgb_model.fit(dummy_X, dummy_y)
105
+ feature_cols = ["ma_5", "ma_20", "rsi", "macd", "vol"]
106
 
107
  # ==========================================
108
+ # 🧠 4. ANALİZ MOTORU
109
  # ==========================================
110
+ def predict_and_analyze():
111
+ # 1) OKX'ten canlı veri çek
112
+ ticker = fetch_okx_ticker()
113
+ candles = fetch_okx_candles(limit=30)
114
+
115
+ if ticker is None or candles is None:
116
+ return "❌ OKX API'sine erişilemedi. Lütfen daha sonra tekrar deneyin.", {}
117
+
118
+ last_price = ticker["last"]
119
+ change_pct = ticker["change_pct"]
120
+ vol24h = ticker["vol24h"]
121
+
122
+ # 2) Teknik göstergeler
123
+ close = candles["close"]
124
+ ma5 = close.rolling(5).mean().iloc[-1]
125
+ ma20 = close.rolling(20).mean().iloc[-1]
126
+ rsi = compute_rsi(close, 14).iloc[-1]
127
+ macd = (close.ewm(span=12).mean() - close.ewm(span=26).mean()).iloc[-1]
128
+
129
+ # 3) XGBoost tahmini
130
+ features = np.array([[ma5, ma20, rsi, macd, vol24h]])
131
  prob_up = float(xgb_model.predict_proba(features)[0][1])
132
  prob_down = 1 - prob_up
133
 
 
136
  "Düşüş (Short) Olasılığı": prob_down,
137
  }
138
 
 
139
  direction = "YUKARI 📈" if prob_up > 0.5 else "AŞAĞI 📉"
140
  confidence = max(prob_up, prob_down) * 100
141
 
142
+ # 4) Groq analizi
143
  prompt = f"""
144
  Sen uzman bir kripto para analisti ve teknik analiz uzmanısın.
145
 
146
+ 📡 OKX Canlı Verileri (BTC/USDT):
147
+ - Son Fiyat: ${last_price:,.2f}
148
+ - 24s Değişim: %{change_pct:+.2f}
149
+ - 24s Hacim: {vol24h:,.0f} BTC
150
+ - 24s Yüksek/Düşük: ${ticker['high24h']:,.2f} / ${ticker['low24h']:,.2f}
151
+
152
+ 📊 Teknik Göstergeler (1H):
153
+ - RSI (14): {rsi:.2f}
154
+ - MA5: ${ma5:,.2f} | MA20: ${ma20:,.2f}
155
+ - MACD: {macd:.4f}
156
 
157
  🤖 XGBoost Model Sonucu:
158
  - Yükseliş Olasılığı: %{prob_up*100:.1f}
 
160
  - Tahmin Yönü: {direction} (Güven: %{confidence:.1f})
161
 
162
  Türkçe bir teknik analiz raporu hazırla. Şu başlıklar bulunsun:
163
+ 1. 🎯 Model Yorumu (XGBoost + teknik göstergelerin mantığı)
164
+ 2. 📈 Teknik Analiz (RSI, MA, MACD; destek/direnç)
165
+ 3. 💡 İşlem Stratejisi (Long/Short, stop-loss, take-profit, risk yönetimi)
166
 
167
+ Yatırım tavsiyesi olmadığını vurgula. Rasyonel ve profesyonel ol.
168
  """
169
 
170
  if client:
 
177
  )
178
  analysis_result = response.choices[0].message.content
179
  except Exception as e:
180
+ analysis_result = f"Groq API Hatası: {e}"
181
  else:
182
+ analysis_result = "GROQ_API_KEY bulunamadı! Hugging Face Secrets'a ekleyin."
183
+
184
+ # Başlık bilgisi
185
+ header = f"**OKX Canlı: ${last_price:,.2f}** (%{change_pct:+.2f}) | RSI: {rsi:.1f} | MA5: ${ma5:,.0f} | MA20: ${ma20:,.0f}\n\n---\n\n"
186
+ return header + analysis_result, prob_dict
187
 
 
188
 
189
  # ==========================================
190
  # 🎨 5. GRADIO ARAYÜZÜ
 
192
  with gr.Blocks(theme=gr.themes.Soft(primary_hue="orange", secondary_hue="slate")) as demo:
193
  gr.Markdown(
194
  """
195
+ # ₿ BTC/USD XGBoost & Groq AI Tahmin Radarı (OKX Canlı)
196
+ Fiyat, hacim ve teknik göstergeler **OKX halka açık API**'sinden otomatik çekilir. **XGBoost** yön tahmini yapar, **Groq** analiz raporu üretir.
197
  """
198
  )
199
 
200
  with gr.Row():
201
  with gr.Column():
202
+ analyze_btn = gr.Button("🔄 OKX'ten Veri Çek ve Analiz Et", variant="primary", size="lg")
203
+ gr.Markdown(
204
+ """
205
+ **Not**: OKX API'si her 2 saniyede 20 istek sınırına sahiptir [citation:7]. Butona çok hızlı basmayın.
206
+ """
207
+ )
 
 
 
 
 
 
208
 
209
  with gr.Column():
210
+ prob_output = gr.Label(label="XGBoost Yön Tahmini")
211
+ analysis_output = gr.Markdown(value="Butona basarak OKX'ten canlı veri çekip analizi başlatın.")
 
 
 
212
 
213
+ analyze_btn.click(
214
  fn=predict_and_analyze,
215
+ inputs=[],
216
  outputs=[analysis_output, prob_output]
217
  )
218
 
219
  gr.Markdown(
220
  """
221
  ---
222
+ ⚠️ **Yatırım Tavsiyesi Değildir**: Bu uygulama eğitim amaçlıdır. Kripto paralar yüksek risk içerir.
223
  """
224
  )
225