File size: 13,500 Bytes
fc115d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
#!/usr/bin/env python3
"""
TFT Training Pipeline

Walk-forward training for the Temporal Fusion Transformer:
1. Fetches 2+ years of historical OHLCV data
2. Creates windowed (lookback, n_features) β†’ (n_horizons,) dataset
3. Trains with quantile loss on MPS/CUDA/CPU
4. Evaluates directional accuracy per horizon
5. Saves best model per asset

Usage:
    python -m src.models.train_forecaster --asset BTCUSDT --epochs 100
    python -m src.models.train_forecaster --asset ETHUSDT --epochs 80 --resume
"""

import argparse
import logging
import os
import sys
import time
from pathlib import Path

import numpy as np
import pandas as pd
import torch
from torch.utils.data import Dataset, DataLoader

# Add project root
PROJECT_ROOT = Path(__file__).parent.parent.parent
sys.path.insert(0, str(PROJECT_ROOT))

from src.models.price_forecaster import (
    TemporalFusionTransformer,
    TFTFeaturePreprocessor,
    QuantileLoss,
    TFTForecaster,
)
from src.backtest.data_loader import download_binance_data

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)


# ─── Dataset ──────────────────────────────────────────────────────────────────

class TimeSeriesDataset(Dataset):
    """
    Sliding window dataset for TFT training.

    Each sample:
    - x: (lookback, n_features) β€” past features
    - y: (n_horizons,) β€” future returns at each horizon
    """

    def __init__(
        self,
        features: np.ndarray,
        targets: np.ndarray,
        lookback: int = 72,
    ):
        self.features = features
        self.targets = targets
        self.lookback = lookback

        # Valid indices: need lookback bars of history AND forward targets to exist
        max_horizon = targets.shape[1]  # number of horizons
        self.valid_indices = []
        for i in range(lookback, len(features)):
            # Check that targets are not all zero (which means we're at the end)
            if i < len(targets) and not np.all(targets[i] == 0):
                self.valid_indices.append(i)

    def __len__(self):
        return len(self.valid_indices)

    def __getitem__(self, idx):
        actual_idx = self.valid_indices[idx]
        x = self.features[actual_idx - self.lookback:actual_idx]
        y = self.targets[actual_idx]
        return (
            torch.tensor(x, dtype=torch.float32),
            torch.tensor(y, dtype=torch.float32),
        )


# ─── Data Loading ─────────────────────────────────────────────────────────────

def fetch_training_data(
    symbol: str = 'BTCUSDT',
    timeframe: str = '1h',
    days: int = 730,  # 2 years
) -> pd.DataFrame:
    """Fetch historical data for training."""
    logger.info(f"πŸ“₯ Fetching {days} days of {timeframe} data for {symbol}...")

    # Convert BTCUSDT β†’ BTC/USDT for the loader
    clean_symbol = symbol.replace('USDT', '/USDT')
    df = download_binance_data(
        symbol=clean_symbol,
        timeframe=timeframe,
        days=days,
    )

    if df is None or df.empty:
        raise ValueError(f"Failed to fetch data for {symbol}")

    logger.info(f"βœ… Fetched {len(df)} candles ({df.index[0]} β†’ {df.index[-1]})")
    return df


def prepare_datasets(
    df: pd.DataFrame,
    lookback: int = 72,
    horizons: list = None,
    train_ratio: float = 0.7,
    val_ratio: float = 0.15,
) -> tuple:
    """
    Prepare train/val/test datasets with walk-forward split.

    Split is chronological (no data leakage):
    [====== train 70% ======][=== val 15% ===][=== test 15% ===]
    """
    horizons = horizons or [1, 4, 12, 24]

    # Compute features and targets
    features = TFTFeaturePreprocessor.prepare_features(df)
    targets = TFTFeaturePreprocessor.prepare_targets(df, horizons)

    n = len(features)
    train_end = int(n * train_ratio)
    val_end = int(n * (train_ratio + val_ratio))

    train_ds = TimeSeriesDataset(features[:train_end], targets[:train_end], lookback)
    val_ds = TimeSeriesDataset(features[train_end:val_end], targets[train_end:val_end], lookback)
    test_ds = TimeSeriesDataset(features[val_end:], targets[val_end:], lookback)

    logger.info(
        f"πŸ“Š Datasets: train={len(train_ds)}, val={len(val_ds)}, test={len(test_ds)} "
        f"(lookback={lookback}, horizons={horizons})"
    )

    return train_ds, val_ds, test_ds


# ─── Training Loop ────────────────────────────────────────────────────────────

def train_tft(
    symbol: str = 'BTCUSDT',
    epochs: int = 100,
    lookback: int = 72,
    hidden_dim: int = 64,
    batch_size: int = 64,
    learning_rate: float = 1e-3,
    patience: int = 15,
    days: int = 730,
    resume: bool = False,
    model_dir: str = './data/models/tft',
):
    """Full TFT training pipeline."""

    # ── Device ──
    if torch.backends.mps.is_available():
        device = torch.device('mps')
    elif torch.cuda.is_available():
        device = torch.device('cuda')
    else:
        device = torch.device('cpu')
    logger.info(f"πŸ–₯️  Device: {device}")

    # ── Data ──
    df = fetch_training_data(symbol, '1h', days)
    train_ds, val_ds, test_ds = prepare_datasets(df, lookback)

    train_loader = DataLoader(train_ds, batch_size=batch_size, shuffle=True, num_workers=0)
    val_loader = DataLoader(val_ds, batch_size=batch_size, shuffle=False, num_workers=0)
    test_loader = DataLoader(test_ds, batch_size=batch_size, shuffle=False, num_workers=0)

    # ── Model ──
    model = TemporalFusionTransformer(
        n_features=TFTFeaturePreprocessor.N_FEATURES,
        hidden_dim=hidden_dim,
    ).to(device)

    # Resume from checkpoint
    model_path = os.path.join(model_dir, f'tft_{symbol.lower()}.pt')
    if resume and os.path.exists(model_path):
        model.load_state_dict(torch.load(model_path, map_location=device, weights_only=True))
        logger.info(f"πŸ“‚ Resumed from {model_path}")

    # ── Training setup ──
    criterion = QuantileLoss()
    optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate, weight_decay=1e-5)
    scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=epochs, eta_min=1e-6)

    # Count parameters
    n_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
    logger.info(f"🧠 Model parameters: {n_params:,}")

    best_val_loss = float('inf')
    patience_counter = 0

    # ── Training loop ──
    logger.info(f"\n{'='*60}")
    logger.info(f"πŸš€ Training TFT for {symbol} ({epochs} epochs)")
    logger.info(f"{'='*60}\n")

    for epoch in range(epochs):
        # ── Train ──
        model.train()
        train_loss = 0.0
        n_train_batches = 0

        for batch_x, batch_y in train_loader:
            batch_x, batch_y = batch_x.to(device), batch_y.to(device)

            optimizer.zero_grad()
            predictions, _ = model(batch_x)
            loss = criterion(predictions, batch_y)
            loss.backward()

            # Gradient clipping
            torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)

            optimizer.step()

            train_loss += loss.item()
            n_train_batches += 1

        train_loss /= max(n_train_batches, 1)

        # ── Validate ──
        model.eval()
        val_loss = 0.0
        n_val_batches = 0
        val_correct = {h: 0 for h in [0, 1, 2, 3]}
        val_total = 0

        with torch.no_grad():
            for batch_x, batch_y in val_loader:
                batch_x, batch_y = batch_x.to(device), batch_y.to(device)

                predictions, _ = model(batch_x)
                loss = criterion(predictions, batch_y)
                val_loss += loss.item()
                n_val_batches += 1

                # Directional accuracy (median predictions)
                median_idx = 1  # 50th percentile
                pred_dir = torch.sign(predictions[:, :, median_idx])
                true_dir = torch.sign(batch_y)

                for h in range(predictions.shape[1]):
                    val_correct[h] += (pred_dir[:, h] == true_dir[:, h]).sum().item()
                val_total += batch_y.shape[0]

        val_loss /= max(n_val_batches, 1)
        scheduler.step()

        # Directional accuracy per horizon
        dir_acc = {h: val_correct[h] / max(val_total, 1) * 100 for h in val_correct}

        # ── Logging ──
        if epoch % 5 == 0 or epoch == epochs - 1:
            logger.info(
                f"Epoch {epoch+1:3d}/{epochs} | "
                f"Train Loss: {train_loss:.6f} | "
                f"Val Loss: {val_loss:.6f} | "
                f"Dir Acc: 1h={dir_acc[0]:.1f}% 4h={dir_acc[1]:.1f}% "
                f"12h={dir_acc[2]:.1f}% 24h={dir_acc[3]:.1f}% | "
                f"LR: {scheduler.get_last_lr()[0]:.2e}"
            )

        # ── Early stopping ──
        if val_loss < best_val_loss:
            best_val_loss = val_loss
            patience_counter = 0

            # Save best model
            os.makedirs(model_dir, exist_ok=True)
            torch.save(model.state_dict(), model_path)
            logger.info(f"  πŸ’Ύ Best model saved (val_loss={val_loss:.6f})")
        else:
            patience_counter += 1
            if patience_counter >= patience:
                logger.info(f"  ⏹️  Early stopping (no improvement for {patience} epochs)")
                break

    # ── Final Evaluation on Test Set ──
    logger.info(f"\n{'='*60}")
    logger.info(f"πŸ“Š Final Evaluation on Test Set")
    logger.info(f"{'='*60}\n")

    # Load best model
    model.load_state_dict(torch.load(model_path, map_location=device, weights_only=True))
    model.eval()

    test_preds = []
    test_targets = []

    with torch.no_grad():
        for batch_x, batch_y in test_loader:
            batch_x = batch_x.to(device)
            predictions, _ = model(batch_x)
            median_preds = predictions[:, :, 1].cpu().numpy()  # 50th percentile
            test_preds.append(median_preds)
            test_targets.append(batch_y.numpy())

    test_preds = np.concatenate(test_preds)
    test_targets = np.concatenate(test_targets)

    horizons = [1, 4, 12, 24]
    for i, h in enumerate(horizons):
        pred_dir = np.sign(test_preds[:, i])
        true_dir = np.sign(test_targets[:, i])

        dir_acc = (pred_dir == true_dir).mean() * 100
        mae = np.mean(np.abs(test_preds[:, i] - test_targets[:, i])) * 100
        corr = np.corrcoef(test_preds[:, i], test_targets[:, i])[0, 1]

        logger.info(
            f"  {h}h horizon: Dir.Acc={dir_acc:.1f}% | MAE={mae:.3f}% | Corr={corr:.3f}"
        )

    # Save evaluation report
    report = {
        'symbol': symbol,
        'epochs_trained': epoch + 1,
        'best_val_loss': float(best_val_loss),
        'test_results': {},
        'n_params': n_params,
        'lookback': lookback,
        'hidden_dim': hidden_dim,
    }

    for i, h in enumerate(horizons):
        pred_dir = np.sign(test_preds[:, i])
        true_dir = np.sign(test_targets[:, i])
        report['test_results'][f'{h}h'] = {
            'directional_accuracy': float((pred_dir == true_dir).mean() * 100),
            'mae': float(np.mean(np.abs(test_preds[:, i] - test_targets[:, i])) * 100),
            'correlation': float(np.corrcoef(test_preds[:, i], test_targets[:, i])[0, 1]),
        }

    import json
    report_path = os.path.join(model_dir, f'tft_{symbol.lower()}_report.json')
    with open(report_path, 'w') as f:
        json.dump(report, f, indent=2)

    logger.info(f"\nβœ… Training complete! Model: {model_path}")
    logger.info(f"πŸ“„ Report: {report_path}")

    return model_path


# ─── CLI ──────────────────────────────────────────────────────────────────────

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Train TFT Price Forecaster')
    parser.add_argument('--asset', type=str, default='BTCUSDT', help='Trading pair')
    parser.add_argument('--epochs', type=int, default=100, help='Training epochs')
    parser.add_argument('--lookback', type=int, default=72, help='Lookback window (hours)')
    parser.add_argument('--hidden-dim', type=int, default=64, help='Hidden dimension')
    parser.add_argument('--batch-size', type=int, default=64, help='Batch size')
    parser.add_argument('--lr', type=float, default=1e-3, help='Learning rate')
    parser.add_argument('--patience', type=int, default=15, help='Early stopping patience')
    parser.add_argument('--days', type=int, default=730, help='Days of data')
    parser.add_argument('--resume', action='store_true', help='Resume from checkpoint')

    args = parser.parse_args()

    train_tft(
        symbol=args.asset,
        epochs=args.epochs,
        lookback=args.lookback,
        hidden_dim=args.hidden_dim,
        batch_size=args.batch_size,
        learning_rate=args.lr,
        patience=args.patience,
        days=args.days,
        resume=args.resume,
    )