| """ |
| XAUUSD Trading Model Training |
| Simple version - generates synthetic data for testing |
| """ |
| import gradio as gr |
| import numpy as np |
| import pandas as pd |
| from sklearn.preprocessing import RobustScaler |
| from sklearn.ensemble import GradientBoostingClassifier |
| from sklearn.metrics import accuracy_score, classification_report |
| import warnings |
| warnings.filterwarnings('ignore') |
|
|
| def generate_data(n_samples=100000): |
| """Generate synthetic XAUUSD-like data""" |
| np.random.seed(42) |
| |
| |
| prices = 1800 + np.cumsum(np.random.randn(n_samples) * 10) |
| |
| data = pd.DataFrame({ |
| 'close': prices, |
| 'open': prices + np.random.randn(n_samples) * 5, |
| 'high': prices + np.abs(np.random.randn(n_samples) * 8), |
| 'low': prices - np.abs(np.random.randn(n_samples) * 8), |
| 'volume': np.random.randint(1000, 100000, n_samples) |
| }) |
| return data |
|
|
| def create_features(df): |
| """Create technical indicators""" |
| features = pd.DataFrame() |
| features['close'] = df['close'] |
| features['open'] = df['open'] |
| features['high'] = df['high'] |
| features['low'] = df['low'] |
| features['volume'] = df['volume'] |
| |
| |
| features['returns'] = df['close'].pct_change() |
| |
| |
| features['sma20'] = df['close'].rolling(20).mean() |
| features['sma50'] = df['close'].rolling(50).mean() |
| |
| |
| ema12 = df['close'].ewm(span=12).mean() |
| ema26 = df['close'].ewm(span=26).mean() |
| macd = ema12 - ema26 |
| features['macd'] = macd |
| features['macd_signal'] = macd.ewm(span=9).mean() |
| features['histogram'] = features['macd'] - features['macd_signal'] |
| |
| |
| delta = df['close'].diff() |
| gain = delta.where(delta > 0, 0).rolling(14).mean() |
| loss = (-delta.where(delta < 0, 0)).rolling(14).mean() |
| rs = gain / loss |
| features['rsi'] = 100 - (100 / (1 + rs)) |
| |
| |
| sma20 = df['close'].rolling(20).mean() |
| std20 = df['close'].rolling(20).std() |
| features['bb_upper'] = sma20 + (std20 * 2) |
| features['bb_lower'] = sma20 - (std20 * 2) |
| |
| |
| future_returns = df['close'].shift(-5) / df['close'] - 1 |
| labels = pd.Series(0, index=df.index) |
| labels[future_returns > 0.005] = 1 |
| labels[future_returns < -0.005] = -1 |
| |
| |
| features['label'] = labels |
| return features.dropna() |
|
|
| def train_model(n_estimators, max_depth, learning_rate): |
| import time |
| start = time.time() |
| |
| yield "π Loading data..." |
| df = generate_data(100000) |
| |
| yield "π§ Creating features..." |
| data = create_features(df) |
| |
| yield "βοΈ Preparing..." |
| X = data.drop('label', axis=1).values |
| y = data['label'].values |
| |
| split_idx = int(len(X) * 0.8) |
| X_train, X_test = X[:split_idx], X[split_idx:] |
| y_train, y_test = y[:split_idx], y[split_idx:] |
| |
| scaler = RobustScaler() |
| X_train_scaled = scaler.fit_transform(X_train) |
| X_test_scaled = scaler.transform(X_test) |
| |
| yield f"π Training (n={n_estimators}, depth={max_depth})..." |
| model = GradientBoostingClassifier( |
| n_estimators=int(n_estimators), |
| max_depth=int(max_depth), |
| learning_rate=learning_rate, |
| subsample=0.8, |
| random_state=42 |
| ) |
| model.fit(X_train_scaled, y_train) |
| |
| yield "π Evaluating..." |
| y_pred = model.predict(X_test_scaled) |
| accuracy = accuracy_score(y_test, y_pred) |
| |
| elapsed = time.time() - start |
| |
| yield { |
| "accuracy": f"{accuracy:.2%}", |
| "time": f"{elapsed:.1f}s", |
| "train_samples": f"{len(X_train):,}", |
| "test_samples": f"{len(X_test):,}", |
| "report": classification_report(y_test, y_pred, target_names=['SELL', 'HOLD', 'BUY']) |
| } |
|
|
| |
| with gr.Blocks() as demo: |
| gr.Markdown("# π€ XAUUSD Trading Model Training") |
| gr.Markdown("**TESTING VERSION** - Uses synthetic data") |
| |
| with gr.Row(): |
| with gr.Column(): |
| n_estimators = gr.Slider(50, 200, value=100, step=10, label="n_estimators") |
| max_depth = gr.Slider(3, 8, value=5, step=1, label="max_depth") |
| learning_rate = gr.Slider(0.01, 0.3, value=0.1, step=0.01, label="learning_rate") |
| train_btn = gr.Button("π Train Model", variant="primary") |
| |
| with gr.Column(): |
| output = gr.JSON(label="Results") |
| report = gr.Textbox(label="Report", lines=8) |
| |
| train_btn.click( |
| fn=train_model, |
| inputs=[n_estimators, max_depth, learning_rate], |
| outputs=[output, report] |
| ) |
| |
| gr.Markdown(""" |
| ## Test Mode |
| - Synthetic 100k samples |
| - 14 features (price + MACD + RSI + BB) |
| - No external dependencies needed |
| """) |
|
|
| demo.launch() |
|
|