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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -28
app.py CHANGED
@@ -1,4 +1,5 @@
1
  import os
 
2
  import numpy as np
3
  import gradio as gr
4
  import xgboost as xgb
@@ -13,13 +14,29 @@ if api_key:
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)
@@ -27,7 +44,6 @@ def train_dummy_model():
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(
@@ -40,17 +56,19 @@ def train_dummy_model():
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,8 +80,9 @@ def predict_and_analyze(last_price, rsi, ma5, ma20, macd, vol):
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}
@@ -76,7 +95,7 @@ def predict_and_analyze(last_price, rsi, ma5, ma20, macd, vol):
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.
@@ -96,48 +115,42 @@ def predict_and_analyze(last_price, rsi, ma5, ma20, macd, vol):
96
  else:
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
 
 
1
  import os
2
+ import requests
3
  import numpy as np
4
  import gradio as gr
5
  import xgboost as xgb
 
14
  client = Groq(api_key=api_key)
15
 
16
  # ==========================================
17
+ # 📡 2. COINMARKETCAP KEYLESS API (Fiyat Çekme)
18
+ # ==========================================
19
+ def fetch_btc_price_cmc():
20
+ """CoinMarketCap Keyless Public API'den anlık BTC fiyatı çeker."""
21
+ try:
22
+ url = "https://pro-api.coinmarketcap.com/public-api/v1/simple/price"
23
+ params = {"symbol": "BTC", "convert": "USD"}
24
+ # Keyless istek: X-CMC_PRO_API_KEY header'ı GÖNDERİLMEZ
25
+ r = requests.get(url, params=params, timeout=10)
26
+ r.raise_for_status()
27
+ data = r.json()
28
+ price = data["data"]["BTC"]["quote"]["USD"]["price"]
29
+ return float(price)
30
+ except Exception as e:
31
+ print(f"CMC API error: {e}")
32
+ return None
33
+
34
+ # ==========================================
35
+ # 🤖 3. XGBOOST MODEL (Sanal Veri)
36
  # ==========================================
37
  def train_dummy_model():
 
38
  np.random.seed(42)
39
  n = 300
 
40
  ma5 = np.random.uniform(55000, 75000, n)
41
  ma20 = ma5 + np.random.normal(0, 500, n)
42
  rsi = np.random.uniform(20, 80, n)
 
44
  vol = np.random.uniform(100, 1000, n)
45
 
46
  X = np.column_stack([ma5, ma20, rsi, macd, vol])
 
47
  y = ((ma5 > ma20) & (rsi < 70)).astype(int)
48
 
49
  model = xgb.XGBClassifier(
 
56
  xgb_model = train_dummy_model()
57
 
58
  # ==========================================
59
+ # 🧠 4. ANALİZ MOTORU
60
  # ==========================================
61
+ def predict_and_analyze(rsi, ma5, ma20, macd, vol):
62
+ # 1) CMC'den anlık fiyatı çek
63
+ last_price = fetch_btc_price_cmc()
64
 
65
+ if last_price is None:
66
+ return "❌ CoinMarketCap API'sine erişilemedi. Lütfen daha sonra tekrar deneyin veya fiyatı manuel girin.", {}
67
+
68
+ # 2) XGBoost tahmini
69
  features = np.array([[ma5, ma20, rsi, macd, vol]])
70
  prob_up = float(xgb_model.predict_proba(features)[0][1])
71
  prob_down = 1 - prob_up
 
72
  direction = "YUKARI 📈" if prob_up > 0.5 else "AŞAĞI 📉"
73
  confidence = max(prob_up, prob_down) * 100
74
 
 
80
  prompt = f"""
81
  Sen uzman bir kripto para analisti ve teknik analiz uzmanısın.
82
 
83
+ 📡 Canlı Fiyat (CoinMarketCap): ${last_price:,.2f}
84
+
85
+ 📊 Teknik Göstergeler (Manuel Giriş):
86
  - RSI (14): {rsi:.2f}
87
  - MA5: ${ma5:,.2f} | MA20: ${ma20:,.2f}
88
  - MACD: {macd:.4f}
 
95
 
96
  Türkçe bir teknik analiz raporu hazırla. Şu başlıklar bulunsun:
97
  1. 🎯 Model Yorumu (XGBoost + teknik göstergelerin mantığı)
98
+ 2. 📈 Teknik Analiz (RSI, MA, MACD; destek/direnç)
99
  3. 💡 İşlem Stratejisi (Long/Short, stop-loss, take-profit, risk yönetimi)
100
 
101
  Yatırım tavsiyesi olmadığını vurgula. Rasyonel ve profesyonel ol.
 
115
  else:
116
  analysis_result = "GROQ_API_KEY bulunamadı! Hugging Face Secrets'a ekleyin."
117
 
118
+ header = f"**Canlı Fiyat (CMC): ${last_price:,.2f}** | RSI: {rsi:.1f} | MA5: ${ma5:,.0f} | MA20: ${ma20:,.0f}\n\n---\n\n"
 
 
 
119
  return header + analysis_result, prob_dict
120
 
121
  # ==========================================
122
+ # 🎨 5. GRADIO ARAYÜZÜ
123
  # ==========================================
124
  with gr.Blocks(theme=gr.themes.Soft(primary_hue="orange", secondary_hue="slate")) as demo:
125
  gr.Markdown(
126
  """
127
+ # ₿ BTC/USD XGBoost & Groq AI Tahmin Radarı (CMC Canlı Fiyat)
128
+ Anlık fiyat **CoinMarketCap Keyless API**'den otomatik çekilir; teknik göstergeleri manuel girin. **XGBoost** yön tahmini yapar, **Groq** analiz raporu üretir.
129
  """
130
  )
131
 
132
  with gr.Row():
133
  with gr.Column():
134
+ gr.Markdown("### 📈 Teknik Göstergeler (Manuel Giriş)")
 
 
 
 
135
  rsi_input = gr.Slider(label="RSI (14)", minimum=0, maximum=100, value=55.0, step=0.1)
136
  with gr.Row():
137
  ma5_input = gr.Number(label="MA5 ($)", value=64800.0)
138
  ma20_input = gr.Number(label="MA20 ($)", value=64000.0)
139
  macd_input = gr.Number(label="MACD Değeri", value=150.0)
140
+ vol_input = gr.Number(label="24s Hacim (BTC)", value=500.0)
141
 
142
+ submit_btn = gr.Button("Canlı Fiyat Çek ve Analiz Et", variant="primary")
143
 
144
  with gr.Column():
145
  gr.Markdown("### 📈 XGBoost Yön Tahmini")
146
  prob_output = gr.Label(label="Olasılık Dağılımı")
147
 
148
  gr.Markdown("### 🧠 Groq Yapay Zeka Analiz Raporu")
149
+ analysis_output = gr.Markdown(value="Butona basarak CMC'den canlı fiyat çekip analizi başlatın.")
150
 
151
  submit_btn.click(
152
  fn=predict_and_analyze,
153
+ inputs=[rsi_input, ma5_input, ma20_input, macd_input, vol_input],
154
  outputs=[analysis_output, prob_output]
155
  )
156