GoshawkVortexAI commited on
Commit
1ea29f9
·
verified ·
1 Parent(s): 7d752da

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +109 -134
app.py CHANGED
@@ -1,7 +1,8 @@
1
  import os
2
  import numpy as np
 
3
  import gradio as gr
4
- from scipy.stats import poisson
5
  from groq import Groq
6
 
7
  # ==========================================
@@ -13,124 +14,102 @@ if api_key:
13
  client = Groq(api_key=api_key)
14
 
15
  # ==========================================
16
- # ⚽ 2. FIFA H2H POISSON GOL TAHMİN MOTORU
17
  # ==========================================
18
- def calculate_poisson_probabilities(home_rating, away_rating, home_form, away_form, home_injuries, away_injuries):
19
- """
20
- FIFA H2H sanal lig için Poisson tabanlı gol tahmini.
21
- - rating: Takım genel gücü (1-99, FIFA Overall Rating)
22
- - form: Son 5 maç formu (0-15 puan)
23
- - injuries: Sakat/cezalı oyuncu sayısı
24
- """
25
- # 1. Takım güçlerini normalize et (FIFA rating 1-99 arası)
26
- home_attack = max(0.5, home_rating / 70.0) # 70 ortalama rating kabul edildi
27
- away_attack = max(0.5, away_rating / 70.0)
28
-
29
- # 2. Form gücü (0-15 -> 0.5-2.0 çarpan)
30
- home_form_power = (home_form / 15.0) * 1.5 + 0.5
31
- away_form_power = (away_form / 15.0) * 1.5 + 0.5
32
-
33
- # 3. Sakatlık cezası: her eksik oyuncu %12 güç kaybı
34
- home_penalty = max(0.4, 1.0 - (home_injuries * 0.12))
35
- away_penalty = max(0.4, 1.0 - (away_injuries * 0.12))
36
-
37
- # 4. Ev sahibi avantajı (FIFA H2H'de ev sahibi ~%15 avantajlı)
38
- home_advantage = 1.15
39
-
40
- # 5. Beklenen gol sayıları (Lambda - λ)
41
- # FIFA H2H ortalama gol: Ev ~1.6, Deplasman ~1.2
42
- base_home_goals = 1.6
43
- base_away_goals = 1.2
44
-
45
- lambda_home = base_home_goals * home_attack * home_form_power * home_penalty * home_advantage
46
- lambda_away = base_away_goals * away_attack * away_form_power * away_penalty
47
-
48
- # Lambda değerlerini makul aralığa sıkıştır
49
- lambda_home = max(0.1, min(4.5, lambda_home))
50
- lambda_away = max(0.1, min(4.5, lambda_away))
51
-
52
- # 6. Poisson matrisi (0-6 gol arası)
53
- max_goals = 6
54
- home_probs = [poisson.pmf(i, lambda_home) for i in range(max_goals + 1)]
55
- away_probs = [poisson.pmf(i, lambda_away) for i in range(max_goals + 1)]
56
-
57
- score_matrix = np.outer(home_probs, away_probs)
58
-
59
- # 7. Sonuç olasılıkları
60
- p_home_win = np.sum(np.tril(score_matrix, -1))
61
- p_draw = np.sum(np.diag(score_matrix))
62
- p_away_win = np.sum(np.triu(score_matrix, 1))
63
-
64
- # 8. Alt/Üst 2.5 gol olasılığı
65
- p_under_25 = 0.0
66
- p_over_25 = 0.0
67
- for i in range(max_goals + 1):
68
- for j in range(max_goals + 1):
69
- if i + j <= 2:
70
- p_under_25 += score_matrix[i, j]
71
- else:
72
- p_over_25 += score_matrix[i, j]
73
-
74
- # 9. Karşılıklı gol (BTTS) olasılığı
75
- p_btts_yes = 0.0
76
- for i in range(1, max_goals + 1):
77
- for j in range(1, max_goals + 1):
78
- p_btts_yes += score_matrix[i, j]
79
-
80
- return (p_home_win, p_draw, p_away_win, lambda_home, lambda_away,
81
- score_matrix, p_under_25, p_over_25, p_btts_yes)
82
 
83
  # ==========================================
84
- # 🧠 3. TAHMİN VE ANALİZ MOTORU
85
  # ==========================================
86
- def predict_and_analyze(home_team, away_team, home_rating, away_rating,
87
- home_form, away_form, home_injuries, away_injuries):
88
- if not home_team or not away_team:
89
- return "Lütfen ev sahibi ve deplasman takımlarının isimlerini giriniz.", {}
90
-
91
- (p_home, p_draw, p_away, lam_home, lam_away,
92
- score_matrix, p_under, p_over, p_btts) = calculate_poisson_probabilities(
93
- home_rating, away_rating, home_form, away_form, home_injuries, away_injuries
 
 
 
 
94
  )
 
 
 
 
 
 
95
 
96
- # En olası skoru bul
97
- max_idx = np.unravel_index(np.argmax(score_matrix), score_matrix.shape)
98
- most_likely_score = f"{max_idx[0]} - {max_idx[1]}"
99
- most_likely_prob = score_matrix[max_idx] * 100
 
 
 
 
 
 
 
100
 
101
- # Gradio grafiği için olasılık sözlüğü
102
  prob_dict = {
103
- f"{home_team} Galibiyeti (1)": float(p_home),
104
- "Beraberlik (X)": float(p_draw),
105
- f"{away_team} Galibiyeti (2)": float(p_away)
106
  }
107
 
 
 
 
 
108
  prompt = f"""
109
- Sen uzman bir FIFA (EA Sports FC) H2H sanal futbol analistisin.
110
- Aşağıdaki verilere göre Türkçe bir maç öncesi analiz raporu hazırla.
111
-
112
- ⚽ Karşılaşma: {home_team} (Ev) vs {away_team} (Deplasman)
113
- 🏆 Format: FIFA H2H Sanal Ligi
114
-
115
- 📊 Takım Güçleri (FIFA Overall Rating):
116
- - {home_team}: Rating {home_rating}, Form (Son 5 Maç) {home_form}/15, Sakat/Cezalı {home_injuries}
117
- - {away_team}: Rating {away_rating}, Form (Son 5 Maç) {away_form}/15, Sakat/Cezalı {away_injuries}
118
-
119
- 📈 Poisson Modeli Sonuçları:
120
- - Beklenen Gol (λ): {home_team} {lam_home:.2f} - {away_team} {lam_away:.2f}
121
- - 1 (Ev Sahibi): %{p_home*100:.1f}
122
- - X (Beraberlik): %{p_draw*100:.1f}
123
- - 2 (Deplasman): %{p_away*100:.1f}
124
- - En Olası Skor: {most_likely_score} (%{most_likely_prob:.1f})
125
- - Alt 2.5: %{p_under*100:.1f} | Üst 2.5: %{p_over*100:.1f}
126
- - Karşılıklı Gol (BTTS): %{p_btts*100:.1f}
127
-
128
- Raporda şu başlıklar bulunsun:
129
- 1. 🎯 Model Yorumu (Poisson ve beklenen gollerin mantığı)
130
- 2. ⚽ Olası Skor ve Gol Tahmini (Alt/Üst, BTTS değerlendirmesi)
131
- 3. 💡 Değerli Bahis Önerisi (+EV değerlendirmesi)
132
-
133
- Yorumların rasyonel, nesnel ve profesyonel olsun.
134
  """
135
 
136
  if client:
@@ -146,44 +125,38 @@ def predict_and_analyze(home_team, away_team, home_rating, away_rating,
146
  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.)"
147
  else:
148
  analysis_result = ("Groq API Anahtarı bulunamadı! Lütfen Hugging Face Space alanına "
149
- "'GROQ_API_KEY' adıyla bir Secret ekleyin. (Yine de yukarıdaki Poisson grafik tahminini görebilirsiniz.)")
150
 
151
  return analysis_result, prob_dict
152
 
153
  # ==========================================
154
- # 🎨 4. GRADIO ARAYÜZÜ
155
  # ==========================================
156
- with gr.Blocks(theme=gr.themes.Soft(primary_hue="green", secondary_hue="slate")) as demo:
157
  gr.Markdown(
158
  """
159
- # ⚽ FIFA H2H Sanal Lig Poisson Tahmin Radarı
160
- Bu uygulama, FIFA H2H sanal lig maçları için **Poisson Dağılımı** kullanarak gol ve sonuç tahminleri üretir; ardından **Groq (GPT-OSS)** yapay zekası ile analiz raporu hazırlar.
161
  """
162
  )
163
 
164
  with gr.Row():
165
  with gr.Column():
166
- gr.Markdown("### 🏟️ Takım İsimleri")
167
- home_input = gr.Textbox(label="Ev Sahibi Takım", value="Real Madrid")
168
- away_input = gr.Textbox(label="Deplasman Takım", value="Barcelona")
169
 
170
- gr.Markdown("### ⭐ Takım Güçleri (FIFA Overall Rating)")
171
- with gr.Row():
172
- home_rating_input = gr.Number(label="Ev Sahibi Rating (1-99)", value=85, precision=0)
173
- away_rating_input = gr.Number(label="Deplasman Rating (1-99)", value=84, precision=0)
174
-
175
- gr.Markdown("### 📊 Form ve Sakatlık Durumu")
176
- with gr.Row():
177
- home_form_input = gr.Slider(label="Ev Form (Son 5 Maç Puanı, Max 15)", minimum=0, maximum=15, value=11, step=1)
178
- away_form_input = gr.Slider(label="Deplasman Form (Son 5 Maç Puanı, Max 15)", minimum=0, maximum=15, value=9, step=1)
179
  with gr.Row():
180
- home_inj_input = gr.Number(label="Ev Sakat/Cezalı Sayısı", value=1, precision=0)
181
- away_inj_input = gr.Number(label="Deplasman Sakat/Cezalı Sayısı", value=2, precision=0)
 
182
 
183
  submit_btn = gr.Button("Analiz Et ve Tahmin Üret", variant="primary")
184
 
185
  with gr.Column():
186
- gr.Markdown("### 📈 Maç Sonucu Olasılıkları (Poisson)")
187
  prob_output = gr.Label(label="Olasılık Dağılımı")
188
 
189
  gr.Markdown("### 🧠 Groq Yapay Zeka Analiz Raporu")
@@ -191,14 +164,16 @@ with gr.Blocks(theme=gr.themes.Soft(primary_hue="green", secondary_hue="slate"))
191
 
192
  submit_btn.click(
193
  fn=predict_and_analyze,
194
- inputs=[
195
- home_input, away_input,
196
- home_rating_input, away_rating_input,
197
- home_form_input, away_form_input,
198
- home_inj_input, away_inj_input
199
- ],
200
  outputs=[analysis_output, prob_output]
201
  )
202
 
 
 
 
 
 
 
 
203
  if __name__ == "__main__":
204
  demo.launch()
 
1
  import os
2
  import numpy as np
3
+ import pandas as pd
4
  import gradio as gr
5
+ import xgboost as xgb
6
  from groq import Groq
7
 
8
  # ==========================================
 
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):
42
+ delta = series.diff()
43
+ gain = delta.clip(lower=0).rolling(period).mean()
44
+ loss = -delta.clip(upper=0).rolling(period).mean()
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
 
 
83
  prob_dict = {
84
+ "Yükseliş (Long) Olasılığı": prob_up,
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}
104
+ - Düşüş Olasılığı: %{prob_down*100:.1f}
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:
 
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Ü
134
  # ==========================================
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")
 
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
+
178
  if __name__ == "__main__":
179
  demo.launch()