GoshawkVortexAI commited on
Commit
ea6360f
·
verified ·
1 Parent(s): 7f2027b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +116 -50
app.py CHANGED
@@ -1,5 +1,7 @@
1
  import os
 
2
  import numpy as np
 
3
  import gradio as gr
4
  import xgboost as xgb
5
  from groq import Groq
@@ -13,42 +15,107 @@ 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)
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 📉"
@@ -62,12 +129,11 @@ 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}
70
- - Hacim: {vol:,.2f}
71
 
72
  🤖 XGBoost Model Sonucu:
73
  - Yükseliş Olasılığı: %{prob_up*100:.1f}
@@ -76,7 +142,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.
@@ -97,8 +163,8 @@ def predict_and_analyze(last_price, rsi, ma5, ma20, macd, vol):
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
 
@@ -108,36 +174,36 @@ def predict_and_analyze(last_price, rsi, ma5, ma20, macd, vol):
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 io
3
  import numpy as np
4
+ import pandas as pd
5
  import gradio as gr
6
  import xgboost as xgb
7
  from groq import Groq
 
15
  client = Groq(api_key=api_key)
16
 
17
  # ==========================================
18
+ # 📊 2. CSV'DEN VERİ OKUMA VE MODEL EĞİTİMİ
19
  # ==========================================
20
+ def compute_rsi(series, period=14):
21
+ delta = series.diff()
22
+ gain = delta.clip(lower=0).rolling(period).mean()
23
+ loss = -delta.clip(upper=0).rolling(period).mean()
24
+ rs = gain / loss
25
+ return 100 - (100 / (1 + rs))
26
+
27
+ def process_csv_and_train(file):
28
+ """Yüklenen CSV'yi işler, göstergeleri hesaplar ve XGBoost modelini eğitir."""
29
+ if file is None:
30
+ return None, None, None
31
+
32
+ try:
33
+ df = pd.read_csv(file.name)
34
+ except Exception as e:
35
+ return None, None, f"CSV okunamadı: {e}"
36
+
37
+ # Sütun isimlerini normalize et (küçük harf)
38
+ df.columns = [c.strip().lower() for c in df.columns]
39
+
40
+ # Gerekli sütun kontrolü
41
+ required = ["close"]
42
+ if not all(col in df.columns for col in required):
43
+ return None, None, f"CSV'de 'close' sütunu bulunamadı. Mevcut sütunlar: {list(df.columns)}"
44
+
45
+ # Sayısal dönüşüm
46
+ for col in ["open", "high", "low", "close", "volume"]:
47
+ if col in df.columns:
48
+ df[col] = pd.to_numeric(df[col], errors="coerce")
49
+
50
+ df = df.dropna(subset=["close"]).reset_index(drop=True)
51
+
52
+ if len(df) < 50:
53
+ return None, None, "CSV'de en az 50 satır veri olmalı."
54
+
55
+ # Teknik göstergeler
56
+ df["ma_5"] = df["close"].rolling(5).mean()
57
+ df["ma_20"] = df["close"].rolling(20).mean()
58
+ df["rsi"] = compute_rsi(df["close"], 14)
59
+ df["macd"] = df["close"].ewm(span=12).mean() - df["close"].ewm(span=26).mean()
60
+ df["target"] = (df["close"].shift(-1) > df["close"]).astype(int)
61
+
62
+ df_model = df.dropna().reset_index(drop=True)
63
+
64
+ if len(df_model) < 20:
65
+ return None, None, "Göstergeler hesaplandıktan sonra yeterli veri kalmadı."
66
+
67
+ features = ["ma_5", "ma_20", "rsi", "macd"]
68
+ if "volume" in df_model.columns:
69
+ features.append("volume")
70
+
71
+ X = df_model[features]
72
+ y = df_model["target"]
73
 
74
  model = xgb.XGBClassifier(
75
  n_estimators=50, max_depth=3, learning_rate=0.1,
76
  objective="binary:logistic", eval_metric="logloss", random_state=42
77
  )
78
  model.fit(X, y)
 
79
 
80
+ # En güncel satırın göstergeleri (tahmin için)
81
+ latest = df_model.iloc[-1]
82
+ latest_features = {
83
+ "ma5": float(latest["ma_5"]),
84
+ "ma20": float(latest["ma_20"]),
85
+ "rsi": float(latest["rsi"]),
86
+ "macd": float(latest["macd"]),
87
+ "last_close": float(latest["close"]),
88
+ "features": features,
89
+ }
90
+ if "volume" in df_model.columns:
91
+ latest_features["volume"] = float(latest["volume"])
92
+
93
+ return model, latest_features, None
94
+
95
+ # Global model değişkenleri
96
+ xgb_model = None
97
+ latest_metrics = None
98
 
99
  # ==========================================
100
+ # 🧠 3. ANALİZ MOTORU
101
  # ==========================================
102
+ def predict_and_analyze(file):
103
+ global xgb_model, latest_metrics
104
+
105
+ model, metrics, err = process_csv_and_train(file)
106
+ if err:
107
+ return err, {}
108
+
109
+ xgb_model = model
110
+ latest_metrics = metrics
111
+
112
+ # Tahmin
113
+ feat_order = metrics["features"]
114
+ feat_values = [metrics[k] for k in ["ma5", "ma20", "rsi", "macd"]]
115
+ if "volume" in feat_order:
116
+ feat_values.append(metrics["volume"])
117
+ features_arr = np.array([feat_values])
118
+ prob_up = float(xgb_model.predict_proba(features_arr)[0][1])
119
  prob_down = 1 - prob_up
120
 
121
  direction = "YUKARI 📈" if prob_up > 0.5 else "AŞAĞI 📉"
 
129
  prompt = f"""
130
  Sen uzman bir kripto para analisti ve teknik analiz uzmanısın.
131
 
132
+ 📊 BTC/USD Son Kapanış (CSV'den): ${metrics['last_close']:,.2f}
133
+ - RSI (14): {metrics['rsi']:.2f}
134
+ - MA5: ${metrics['ma5']:,.2f} | MA20: ${metrics['ma20']:,.2f}
135
+ - MACD: {metrics['macd']:.4f}
136
+ {f"- Hacim: {metrics['volume']:,.2f}" if 'volume' in metrics else ""}
 
137
 
138
  🤖 XGBoost Model Sonucu:
139
  - Yükseliş Olasılığı: %{prob_up*100:.1f}
 
142
 
143
  Türkçe bir teknik analiz raporu hazırla. Şu başlıklar bulunsun:
144
  1. 🎯 Model Yorumu (XGBoost + teknik göstergelerin mantığı)
145
+ 2. 📈 Teknik Analiz (RSI, MA, MACD; destek/direnç)
146
  3. 💡 İşlem Stratejisi (Long/Short, stop-loss, take-profit, risk yönetimi)
147
 
148
  Yatırım tavsiyesi olmadığını vurgula. Rasyonel ve profesyonel ol.
 
163
  analysis_result = "GROQ_API_KEY bulunamadı! Hugging Face Secrets'a ekleyin."
164
 
165
  header = (
166
+ f"**Son Kapanış: ${metrics['last_close']:,.2f}** | RSI: {metrics['rsi']:.1f} | "
167
+ f"MA5: ${metrics['ma5']:,.0f} | MA20: ${metrics['ma20']:,.0f}\n\n---\n\n"
168
  )
169
  return header + analysis_result, prob_dict
170
 
 
174
  with gr.Blocks(theme=gr.themes.Soft(primary_hue="orange", secondary_hue="slate")) as demo:
175
  gr.Markdown(
176
  """
177
+ # ₿ BTC/USD XGBoost & Groq AI Tahmin Radarı (CSV Yükleme)
178
+ **Yahoo Finance (yfinance)** ile indirdiğiniz BTC-USD CSV dosyasını yükleyin. Model CSV üzerinden eğitilir, XGBoost yön tahmini yapar, Groq analiz raporu üretir. **Hiçbir dış API çağrısı yapılmaz.**
179
  """
180
  )
181
 
182
  with gr.Row():
183
  with gr.Column():
184
+ gr.Markdown("### 📂 CSV Dosyası Yükle")
185
+ file_input = gr.File(label="BTC-USD CSV (Date, Open, High, Low, Close, Volume)", file_types=[".csv"])
186
+ gr.Markdown(
187
+ """
188
+ **İpucu**: `pip install yfinance` ile şu şekilde indirebilirsiniz:
189
+ ```python
190
+ import yfinance as yf
191
+ yf.download("BTC-USD", period="2y", interval="1d").to_csv("btc.csv")
192
+ ```
193
+ """
194
+ )
195
+ submit_btn = gr.Button("CSV'yi Yükle ve Analiz Et", variant="primary")
196
 
197
  with gr.Column():
198
  gr.Markdown("### 📈 XGBoost Yön Tahmini")
199
  prob_output = gr.Label(label="Olasılık Dağılımı")
200
 
201
  gr.Markdown("### 🧠 Groq Yapay Zeka Analiz Raporu")
202
+ analysis_output = gr.Markdown(value="CSV dosyasını yükleyip butona basın.")
203
 
204
  submit_btn.click(
205
  fn=predict_and_analyze,
206
+ inputs=[file_input],
207
  outputs=[analysis_output, prob_output]
208
  )
209