Spaces:
Sleeping
Sleeping
Update app.py
Browse files
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 |
-
#
|
| 17 |
# ==========================================
|
| 18 |
-
def
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
|
| 42 |
# ==========================================
|
| 43 |
-
# 🧠 3. ANALİZ MOTORU
|
| 44 |
# ==========================================
|
| 45 |
-
def predict_and_analyze(
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
| 66 |
-
-
|
| 67 |
-
-
|
| 68 |
-
-
|
| 69 |
-
-
|
| 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ç
|
| 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"**
|
| 101 |
-
f"
|
| 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ı (
|
| 112 |
-
|
| 113 |
"""
|
| 114 |
)
|
| 115 |
|
| 116 |
with gr.Row():
|
| 117 |
with gr.Column():
|
| 118 |
-
gr.Markdown("###
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
submit_btn = gr.Button("
|
| 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="
|
| 137 |
|
| 138 |
submit_btn.click(
|
| 139 |
fn=predict_and_analyze,
|
| 140 |
-
inputs=[
|
| 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 |
|