Update app.py
Browse files
app.py
CHANGED
|
@@ -7,11 +7,12 @@ from sklearn.ensemble import RandomForestClassifier
|
|
| 7 |
from sklearn.preprocessing import MinMaxScaler
|
| 8 |
import joblib
|
| 9 |
import os
|
| 10 |
-
import
|
|
|
|
| 11 |
|
| 12 |
-
|
|
|
|
| 13 |
|
| 14 |
-
# π§ Konfigurasi
|
| 15 |
SYMBOL = "ETH/USDT"
|
| 16 |
TIMEFRAME = "4h"
|
| 17 |
FEE = 0.0015
|
|
@@ -20,13 +21,20 @@ MODEL_PATH = "rf_model.pkl"
|
|
| 20 |
SCALER_PATH = "scaler.pkl"
|
| 21 |
|
| 22 |
def fetch_data(symbol: str, timeframe: str, limit: int = 2000) -> pd.DataFrame:
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
ohlcv = exchange.fetch_ohlcv(symbol, timeframe, limit=limit)
|
| 25 |
df = pd.DataFrame(ohlcv, columns=["timestamp", "open", "high", "low", "close", "volume"])
|
| 26 |
df["timestamp"] = pd.to_datetime(df["timestamp"], unit="ms")
|
|
|
|
| 27 |
return df
|
| 28 |
|
| 29 |
def prepare_dataset(df: pd.DataFrame):
|
|
|
|
| 30 |
df = df.copy()
|
| 31 |
df.ta.rsi(append=True)
|
| 32 |
df.ta.macd(append=True)
|
|
@@ -49,12 +57,13 @@ def prepare_dataset(df: pd.DataFrame):
|
|
| 49 |
y = np.array(y_list)
|
| 50 |
scaler = MinMaxScaler()
|
| 51 |
X_scaled = scaler.fit_transform(X)
|
|
|
|
| 52 |
return X_scaled, y, idx_list, df, scaler
|
| 53 |
|
| 54 |
def run_train():
|
| 55 |
try:
|
| 56 |
if os.path.exists(MODEL_PATH):
|
| 57 |
-
return {"message": "Model sudah ada. Hapus
|
| 58 |
|
| 59 |
df = fetch_data(SYMBOL, TIMEFRAME)
|
| 60 |
X, y, idx, df_full, scaler = prepare_dataset(df)
|
|
@@ -63,7 +72,8 @@ def run_train():
|
|
| 63 |
X_train, X_test = X[:split], X[split:]
|
| 64 |
y_train, y_test = y[:split], y[split:]
|
| 65 |
|
| 66 |
-
|
|
|
|
| 67 |
model.fit(X_train, y_train)
|
| 68 |
acc = float(model.score(X_test, y_test))
|
| 69 |
|
|
@@ -89,20 +99,22 @@ def run_train():
|
|
| 89 |
profit_factor = gross_profit / gross_loss if gross_loss > 0 else float("inf")
|
| 90 |
|
| 91 |
return {
|
|
|
|
| 92 |
"accuracy_test": round(acc, 4),
|
| 93 |
"profit_factor": round(profit_factor, 3),
|
| 94 |
"net_profit_pct": round(sum(pnl_list) * 100, 3),
|
| 95 |
"wins": wins, "losses": losses,
|
| 96 |
"win_rate_pct": round(wins / len(pnl_list) * 100, 2) if pnl_list else 0,
|
| 97 |
-
"message": "Model trained & backtested successfully"
|
| 98 |
}
|
| 99 |
except Exception as e:
|
| 100 |
-
|
|
|
|
| 101 |
|
| 102 |
def run_predict():
|
| 103 |
try:
|
| 104 |
if not os.path.exists(MODEL_PATH):
|
| 105 |
-
return {"
|
| 106 |
|
| 107 |
df = fetch_data(SYMBOL, TIMEFRAME, limit=WINDOW + 10)
|
| 108 |
_, _, _, df_full, scaler = prepare_dataset(df)
|
|
@@ -113,17 +125,18 @@ def run_predict():
|
|
| 113 |
pred = int(model.predict(latest_scaled)[0])
|
| 114 |
|
| 115 |
return {
|
|
|
|
| 116 |
"symbol": SYMBOL, "timeframe": TIMEFRAME,
|
| 117 |
"prediction": "BUY (Hold 4h)" if pred == 1 else "HOLD/SELL",
|
| 118 |
"logic": "Prediksi >0.15% movement dalam 4 jam ke depan"
|
| 119 |
}
|
| 120 |
except Exception as e:
|
| 121 |
-
|
|
|
|
| 122 |
|
| 123 |
-
# π¨ Gradio UI
|
| 124 |
with gr.Blocks(title="Crypto ML Predictor") as demo:
|
| 125 |
gr.Markdown("## π Crypto ML Strategy (ETH/USDT 4h)")
|
| 126 |
-
gr.Markdown("
|
| 127 |
with gr.Row():
|
| 128 |
train_btn = gr.Button("π Train Model & Backtest")
|
| 129 |
train_out = gr.JSON(label="Hasil Training & Backtest")
|
|
@@ -133,7 +146,6 @@ with gr.Blocks(title="Crypto ML Predictor") as demo:
|
|
| 133 |
|
| 134 |
train_btn.click(run_train, outputs=train_out)
|
| 135 |
pred_btn.click(run_predict, outputs=pred_out)
|
| 136 |
-
gr.Markdown("
|
| 137 |
|
| 138 |
-
|
| 139 |
-
demo.queue()
|
|
|
|
| 7 |
from sklearn.preprocessing import MinMaxScaler
|
| 8 |
import joblib
|
| 9 |
import os
|
| 10 |
+
import logging
|
| 11 |
+
import sys
|
| 12 |
|
| 13 |
+
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
|
| 14 |
+
logger = logging.getLogger("crypto_ml")
|
| 15 |
|
|
|
|
| 16 |
SYMBOL = "ETH/USDT"
|
| 17 |
TIMEFRAME = "4h"
|
| 18 |
FEE = 0.0015
|
|
|
|
| 21 |
SCALER_PATH = "scaler.pkl"
|
| 22 |
|
| 23 |
def fetch_data(symbol: str, timeframe: str, limit: int = 2000) -> pd.DataFrame:
|
| 24 |
+
logger.info("Fetching data from Binance...")
|
| 25 |
+
exchange = ccxt.binance({
|
| 26 |
+
"enableRateLimit": True,
|
| 27 |
+
"timeout": 30000,
|
| 28 |
+
"options": {"defaultType": "spot"}
|
| 29 |
+
})
|
| 30 |
ohlcv = exchange.fetch_ohlcv(symbol, timeframe, limit=limit)
|
| 31 |
df = pd.DataFrame(ohlcv, columns=["timestamp", "open", "high", "low", "close", "volume"])
|
| 32 |
df["timestamp"] = pd.to_datetime(df["timestamp"], unit="ms")
|
| 33 |
+
logger.info(f"Fetched {len(df)} candles.")
|
| 34 |
return df
|
| 35 |
|
| 36 |
def prepare_dataset(df: pd.DataFrame):
|
| 37 |
+
logger.info("Preparing dataset & indicators...")
|
| 38 |
df = df.copy()
|
| 39 |
df.ta.rsi(append=True)
|
| 40 |
df.ta.macd(append=True)
|
|
|
|
| 57 |
y = np.array(y_list)
|
| 58 |
scaler = MinMaxScaler()
|
| 59 |
X_scaled = scaler.fit_transform(X)
|
| 60 |
+
logger.info(f"Dataset ready: {X.shape[0]} samples, {X.shape[1]} features.")
|
| 61 |
return X_scaled, y, idx_list, df, scaler
|
| 62 |
|
| 63 |
def run_train():
|
| 64 |
try:
|
| 65 |
if os.path.exists(MODEL_PATH):
|
| 66 |
+
return {"status": "β οΈ Info", "message": "Model sudah ada. Hapus file .pkl di Files tab untuk retrain."}
|
| 67 |
|
| 68 |
df = fetch_data(SYMBOL, TIMEFRAME)
|
| 69 |
X, y, idx, df_full, scaler = prepare_dataset(df)
|
|
|
|
| 72 |
X_train, X_test = X[:split], X[split:]
|
| 73 |
y_train, y_test = y[:split], y[split:]
|
| 74 |
|
| 75 |
+
logger.info("Training RandomForest...")
|
| 76 |
+
model = RandomForestClassifier(n_estimators=500, max_depth=None, random_state=42, n_jobs=-1)
|
| 77 |
model.fit(X_train, y_train)
|
| 78 |
acc = float(model.score(X_test, y_test))
|
| 79 |
|
|
|
|
| 99 |
profit_factor = gross_profit / gross_loss if gross_loss > 0 else float("inf")
|
| 100 |
|
| 101 |
return {
|
| 102 |
+
"status": "β
Success",
|
| 103 |
"accuracy_test": round(acc, 4),
|
| 104 |
"profit_factor": round(profit_factor, 3),
|
| 105 |
"net_profit_pct": round(sum(pnl_list) * 100, 3),
|
| 106 |
"wins": wins, "losses": losses,
|
| 107 |
"win_rate_pct": round(wins / len(pnl_list) * 100, 2) if pnl_list else 0,
|
| 108 |
+
"message": "Model trained & backtested successfully."
|
| 109 |
}
|
| 110 |
except Exception as e:
|
| 111 |
+
logger.error(f"Training failed: {e}")
|
| 112 |
+
return {"status": "β Error", "message": str(e)}
|
| 113 |
|
| 114 |
def run_predict():
|
| 115 |
try:
|
| 116 |
if not os.path.exists(MODEL_PATH):
|
| 117 |
+
return {"status": "β Error", "message": "Model belum dilatih. Klik 'Train' terlebih dahulu."}
|
| 118 |
|
| 119 |
df = fetch_data(SYMBOL, TIMEFRAME, limit=WINDOW + 10)
|
| 120 |
_, _, _, df_full, scaler = prepare_dataset(df)
|
|
|
|
| 125 |
pred = int(model.predict(latest_scaled)[0])
|
| 126 |
|
| 127 |
return {
|
| 128 |
+
"status": "β
Prediction",
|
| 129 |
"symbol": SYMBOL, "timeframe": TIMEFRAME,
|
| 130 |
"prediction": "BUY (Hold 4h)" if pred == 1 else "HOLD/SELL",
|
| 131 |
"logic": "Prediksi >0.15% movement dalam 4 jam ke depan"
|
| 132 |
}
|
| 133 |
except Exception as e:
|
| 134 |
+
logger.error(f"Prediction failed: {e}")
|
| 135 |
+
return {"status": "β Error", "message": str(e)}
|
| 136 |
|
|
|
|
| 137 |
with gr.Blocks(title="Crypto ML Predictor") as demo:
|
| 138 |
gr.Markdown("## π Crypto ML Strategy (ETH/USDT 4h)")
|
| 139 |
+
gr.Markdown("Paper: 2105.06827v3 | Python 3.10 | Gradio Queue Enabled")
|
| 140 |
with gr.Row():
|
| 141 |
train_btn = gr.Button("π Train Model & Backtest")
|
| 142 |
train_out = gr.JSON(label="Hasil Training & Backtest")
|
|
|
|
| 146 |
|
| 147 |
train_btn.click(run_train, outputs=train_out)
|
| 148 |
pred_btn.click(run_predict, outputs=pred_out)
|
| 149 |
+
gr.Markdown("π‘ *Check 'App Logs' di tab Space untuk debugging real-time.*")
|
| 150 |
|
| 151 |
+
demo.queue(default_concurrency_limit=1)
|
|
|