Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
import os
|
| 2 |
import io
|
|
|
|
| 3 |
import numpy as np
|
| 4 |
import pandas as pd
|
| 5 |
import gradio as gr
|
|
@@ -15,7 +16,7 @@ if api_key:
|
|
| 15 |
client = Groq(api_key=api_key)
|
| 16 |
|
| 17 |
# ==========================================
|
| 18 |
-
# 📊 2.
|
| 19 |
# ==========================================
|
| 20 |
def compute_rsi(series, period=14):
|
| 21 |
delta = series.diff()
|
|
@@ -24,25 +25,33 @@ def compute_rsi(series, period=14):
|
|
| 24 |
rs = gain / loss
|
| 25 |
return 100 - (100 / (1 + rs))
|
| 26 |
|
| 27 |
-
def
|
| 28 |
-
"""
|
| 29 |
-
if file is None:
|
| 30 |
-
return None, None, None
|
| 31 |
-
|
| 32 |
try:
|
| 33 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
except Exception as e:
|
| 35 |
-
return None,
|
| 36 |
|
| 37 |
-
|
|
|
|
| 38 |
df.columns = [c.strip().lower() for c in df.columns]
|
| 39 |
|
| 40 |
-
#
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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")
|
|
@@ -77,45 +86,43 @@ def process_csv_and_train(file):
|
|
| 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 |
-
|
|
|
|
| 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 |
-
|
| 92 |
|
| 93 |
-
return model,
|
| 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(
|
| 103 |
-
|
|
|
|
| 104 |
|
| 105 |
-
|
|
|
|
| 106 |
if err:
|
| 107 |
return err, {}
|
| 108 |
|
| 109 |
-
|
| 110 |
-
|
|
|
|
|
|
|
| 111 |
|
| 112 |
-
# Tahmin
|
| 113 |
-
feat_order = metrics["features"]
|
| 114 |
feat_values = [metrics[k] for k in ["ma5", "ma20", "rsi", "macd"]]
|
| 115 |
-
if "volume" in
|
| 116 |
feat_values.append(metrics["volume"])
|
| 117 |
features_arr = np.array([feat_values])
|
| 118 |
-
prob_up = float(
|
| 119 |
prob_down = 1 - prob_up
|
| 120 |
|
| 121 |
direction = "YUKARI 📈" if prob_up > 0.5 else "AŞAĞI 📉"
|
|
@@ -163,7 +170,7 @@ def predict_and_analyze(file):
|
|
| 163 |
analysis_result = "GROQ_API_KEY bulunamadı! Hugging Face Secrets'a ekleyin."
|
| 164 |
|
| 165 |
header = (
|
| 166 |
-
f"**Son Kapanış
|
| 167 |
f"MA5: ${metrics['ma5']:,.0f} | MA20: ${metrics['ma20']:,.0f}\n\n---\n\n"
|
| 168 |
)
|
| 169 |
return header + analysis_result, prob_dict
|
|
@@ -174,36 +181,38 @@ def predict_and_analyze(file):
|
|
| 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
|
| 178 |
-
|
| 179 |
"""
|
| 180 |
)
|
| 181 |
|
| 182 |
with gr.Row():
|
| 183 |
with gr.Column():
|
| 184 |
-
gr.Markdown("###
|
| 185 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 186 |
gr.Markdown(
|
| 187 |
"""
|
| 188 |
-
**
|
| 189 |
-
``
|
| 190 |
-
|
| 191 |
-
yf.download("BTC-USD", period="2y", interval="1d").to_csv("btc.csv")
|
| 192 |
-
```
|
| 193 |
"""
|
| 194 |
)
|
| 195 |
-
submit_btn = gr.Button("CSV'yi
|
| 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
|
| 203 |
|
| 204 |
submit_btn.click(
|
| 205 |
fn=predict_and_analyze,
|
| 206 |
-
inputs=[
|
| 207 |
outputs=[analysis_output, prob_output]
|
| 208 |
)
|
| 209 |
|
|
|
|
| 1 |
import os
|
| 2 |
import io
|
| 3 |
+
import requests
|
| 4 |
import numpy as np
|
| 5 |
import pandas as pd
|
| 6 |
import gradio as gr
|
|
|
|
| 16 |
client = Groq(api_key=api_key)
|
| 17 |
|
| 18 |
# ==========================================
|
| 19 |
+
# 📊 2. YARDIMCI FONKSİYONLAR
|
| 20 |
# ==========================================
|
| 21 |
def compute_rsi(series, period=14):
|
| 22 |
delta = series.diff()
|
|
|
|
| 25 |
rs = gain / loss
|
| 26 |
return 100 - (100 / (1 + rs))
|
| 27 |
|
| 28 |
+
def load_csv_from_url(url):
|
| 29 |
+
"""Verilen URL'den CSV indirir ve DataFrame döndürür."""
|
|
|
|
|
|
|
|
|
|
| 30 |
try:
|
| 31 |
+
headers = {"User-Agent": "Mozilla/5.0"}
|
| 32 |
+
r = requests.get(url, headers=headers, timeout=20)
|
| 33 |
+
r.raise_for_status()
|
| 34 |
+
df = pd.read_csv(io.StringIO(r.text))
|
| 35 |
+
return df, None
|
| 36 |
except Exception as e:
|
| 37 |
+
return None, f"CSV indirilemedi: {e}"
|
| 38 |
|
| 39 |
+
def process_dataframe(df):
|
| 40 |
+
"""CSV DataFrame'ini işler, göstergeleri hesaplar ve XGBoost modelini eğitir."""
|
| 41 |
df.columns = [c.strip().lower() for c in df.columns]
|
| 42 |
|
| 43 |
+
# Sütun eşleştirme (farklı CSV formatlarına tolerans)
|
| 44 |
+
col_map = {
|
| 45 |
+
"date": "date", "datetime": "date", "timestamp": "date",
|
| 46 |
+
"open": "open", "high": "high", "low": "low",
|
| 47 |
+
"close": "close", "adj close": "close", "price": "close",
|
| 48 |
+
"volume": "volume", "vol": "volume"
|
| 49 |
+
}
|
| 50 |
+
df = df.rename(columns={c: col_map[c] for c in df.columns if c in col_map})
|
| 51 |
+
|
| 52 |
+
if "close" not in df.columns:
|
| 53 |
+
return None, None, f"'close' sütunu bulunamadı. Mevcut sütunlar: {list(df.columns)}"
|
| 54 |
|
|
|
|
| 55 |
for col in ["open", "high", "low", "close", "volume"]:
|
| 56 |
if col in df.columns:
|
| 57 |
df[col] = pd.to_numeric(df[col], errors="coerce")
|
|
|
|
| 86 |
)
|
| 87 |
model.fit(X, y)
|
| 88 |
|
|
|
|
| 89 |
latest = df_model.iloc[-1]
|
| 90 |
+
metrics = {
|
| 91 |
+
"last_close": float(latest["close"]),
|
| 92 |
"ma5": float(latest["ma_5"]),
|
| 93 |
"ma20": float(latest["ma_20"]),
|
| 94 |
"rsi": float(latest["rsi"]),
|
| 95 |
"macd": float(latest["macd"]),
|
|
|
|
| 96 |
"features": features,
|
| 97 |
}
|
| 98 |
if "volume" in df_model.columns:
|
| 99 |
+
metrics["volume"] = float(latest["volume"])
|
| 100 |
|
| 101 |
+
return model, metrics, None
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
|
| 103 |
# ==========================================
|
| 104 |
# 🧠 3. ANALİZ MOTORU
|
| 105 |
# ==========================================
|
| 106 |
+
def predict_and_analyze(csv_url):
|
| 107 |
+
if not csv_url:
|
| 108 |
+
return "Lütfen bir CSV linki giriniz.", {}
|
| 109 |
|
| 110 |
+
# 1) CSV indir
|
| 111 |
+
df, err = load_csv_from_url(csv_url)
|
| 112 |
if err:
|
| 113 |
return err, {}
|
| 114 |
|
| 115 |
+
# 2) Modeli eğit
|
| 116 |
+
model, metrics, err = process_dataframe(df)
|
| 117 |
+
if err:
|
| 118 |
+
return err, {}
|
| 119 |
|
| 120 |
+
# 3) Tahmin
|
|
|
|
| 121 |
feat_values = [metrics[k] for k in ["ma5", "ma20", "rsi", "macd"]]
|
| 122 |
+
if "volume" in metrics:
|
| 123 |
feat_values.append(metrics["volume"])
|
| 124 |
features_arr = np.array([feat_values])
|
| 125 |
+
prob_up = float(model.predict_proba(features_arr)[0][1])
|
| 126 |
prob_down = 1 - prob_up
|
| 127 |
|
| 128 |
direction = "YUKARI 📈" if prob_up > 0.5 else "AŞAĞI 📉"
|
|
|
|
| 170 |
analysis_result = "GROQ_API_KEY bulunamadı! Hugging Face Secrets'a ekleyin."
|
| 171 |
|
| 172 |
header = (
|
| 173 |
+
f"**CSV: Son Kapanış ${metrics['last_close']:,.2f}** | RSI: {metrics['rsi']:.1f} | "
|
| 174 |
f"MA5: ${metrics['ma5']:,.0f} | MA20: ${metrics['ma20']:,.0f}\n\n---\n\n"
|
| 175 |
)
|
| 176 |
return header + analysis_result, prob_dict
|
|
|
|
| 181 |
with gr.Blocks(theme=gr.themes.Soft(primary_hue="orange", secondary_hue="slate")) as demo:
|
| 182 |
gr.Markdown(
|
| 183 |
"""
|
| 184 |
+
# ₿ BTC/USD XGBoost & Groq AI Tahmin Radarı (CSV Linki)
|
| 185 |
+
Bir CSV linki girin; kod dosyayı indirir, göstergeleri hesaplar, **XGBoost** modelini eğitir ve **Groq** analiz raporu üretir.
|
| 186 |
"""
|
| 187 |
)
|
| 188 |
|
| 189 |
with gr.Row():
|
| 190 |
with gr.Column():
|
| 191 |
+
gr.Markdown("### 🔗 CSV Linki")
|
| 192 |
+
url_input = gr.Textbox(
|
| 193 |
+
label="CSV URL",
|
| 194 |
+
placeholder="https://.../btc_usd.csv",
|
| 195 |
+
value=""
|
| 196 |
+
)
|
| 197 |
gr.Markdown(
|
| 198 |
"""
|
| 199 |
+
**Örnek linkler:**
|
| 200 |
+
- `https://raw.githubusercontent.com/.../btc_usd.csv`
|
| 201 |
+
- Kaggle'dan indirdiğiniz CSV'yi GitHub'a yükleyip raw linkini kullanabilirsiniz.
|
|
|
|
|
|
|
| 202 |
"""
|
| 203 |
)
|
| 204 |
+
submit_btn = gr.Button("CSV'yi İndir ve Analiz Et", variant="primary")
|
| 205 |
|
| 206 |
with gr.Column():
|
| 207 |
gr.Markdown("### 📈 XGBoost Yön Tahmini")
|
| 208 |
prob_output = gr.Label(label="Olasılık Dağılımı")
|
| 209 |
|
| 210 |
gr.Markdown("### 🧠 Groq Yapay Zeka Analiz Raporu")
|
| 211 |
+
analysis_output = gr.Markdown(value="CSV linkini girip butona basın.")
|
| 212 |
|
| 213 |
submit_btn.click(
|
| 214 |
fn=predict_and_analyze,
|
| 215 |
+
inputs=[url_input],
|
| 216 |
outputs=[analysis_output, prob_output]
|
| 217 |
)
|
| 218 |
|