Download src/experiments/v2/train_gru_pred20.py from GoldenGrapeGentleman1/FinMM-Project-FinMM: direct link, hf CLI and curl.
- Browser
- Download file 8.11 kB
-
https://huggingface.co/GoldenGrapeGentleman1/FinMM-Project-FinMM/resolve/main/src/experiments/v2/train_gru_pred20.py
- Command line
-
hf download hf://GoldenGrapeGentleman1/FinMM-Project-FinMM/src/experiments/v2/train_gru_pred20.py
-
curl -L -o train_gru_pred20.py https://huggingface.co/GoldenGrapeGentleman1/FinMM-Project-FinMM/resolve/main/src/experiments/v2/train_gru_pred20.py
8.11 kB
| """ | |
| Training: GRU Baseline pred20. | |
| Standard GRU baseline without advanced optimizations. | |
| Usage: python train_gru_pred20.py --epochs 30 --batch_size 32 | |
| """ | |
| import torch | |
| import torch.nn as nn | |
| import torch.optim as optim | |
| import sys, os | |
| import numpy as np | |
| import pandas as pd | |
| from torch.utils.data import Dataset, DataLoader | |
| import argparse | |
| # ========== Command Line Arguments ========== | |
| parser = argparse.ArgumentParser(description='GRU Baseline Training') | |
| parser.add_argument('--max_stocks', type=int, default=300, help='Max number of stocks') | |
| parser.add_argument('--epochs', type=int, default=20, help='Max training epochs') | |
| parser.add_argument('--batch_size', type=int, default=32, help='Batch size') | |
| parser.add_argument('--lr', type=float, default=5e-5, help='Learning rate') | |
| parser.add_argument('--seq_len', type=int, default=96, help='Input sequence length (days)') | |
| parser.add_argument('--pred_len', type=int, default=20, help='Prediction length (days)') | |
| parser.add_argument('--patience', type=int, default=3, help='Early stopping patience') | |
| args = parser.parse_args() | |
| sys.path.insert(0, '/workspace/Finance/Project_FinMM/src/models') | |
| print(f"\nGRU Baseline pred{args.pred_len} | {args.max_stocks} stocks | batch={args.batch_size} | lr={args.lr}") | |
| # ========== Dataset Definition ========== | |
| class SimplePriceDataset(Dataset): | |
| """Predict price directly (log transform, no normalization).""" | |
| def __init__(self, data_dir, mode, seq_len, pred_len, max_stocks): | |
| self.seq_len = seq_len | |
| self.samples = [] | |
| # Time split | |
| if mode == 'train': | |
| start, end = pd.to_datetime('2006-01-01'), pd.to_datetime('2022-12-31') | |
| elif mode == 'val': | |
| start, end = pd.to_datetime('2023-01-01'), pd.to_datetime('2023-12-31') | |
| else: | |
| start, end = pd.to_datetime('2024-01-01'), pd.to_datetime('2025-12-31') | |
| stock_count = 0 | |
| for market in ['HS300_time_series/HS300_time_series', 'S&P500_time_series/S&P500_time_series']: | |
| if stock_count >= max_stocks: | |
| break | |
| csv_dir = os.path.join(data_dir, market) | |
| if not os.path.exists(csv_dir): | |
| continue | |
| for csv_file in os.listdir(csv_dir): | |
| if stock_count >= max_stocks: | |
| break | |
| if csv_file.endswith('.csv'): | |
| try: | |
| df = pd.read_csv(f'{csv_dir}/{csv_file}') | |
| if len(df) < 5000: | |
| continue | |
| df['Date'] = pd.to_datetime(df['Date'], utc=True).dt.tz_convert(None) | |
| df_f = df[(df['Date'] >= start) & (df['Date'] <= end)] | |
| if len(df_f) < seq_len + pred_len: | |
| continue | |
| # Log transform (price prediction) | |
| data_log = np.log(df_f[['Open', 'High', 'Low', 'Close', 'Volume']].values + 1) | |
| for i in range(len(data_log) - seq_len - pred_len): | |
| self.samples.append(data_log[i:i+seq_len+pred_len]) | |
| stock_count += 1 | |
| except: | |
| continue | |
| def __len__(self): | |
| return len(self.samples) | |
| def __getitem__(self, idx): | |
| data = self.samples[idx] | |
| return torch.FloatTensor(data[:self.seq_len]), torch.FloatTensor(data[self.seq_len:, 3]) | |
| # ========== Load Data ========== | |
| from model_gru import GRUBaseline | |
| class Cfg: | |
| history_len = args.seq_len | |
| pred_len = args.pred_len | |
| c_in = 5 | |
| DATA_DIR = '/workspace/Finance/fin-mm/data/finmultitime_hf/time_series' | |
| train = SimplePriceDataset(DATA_DIR, 'train', args.seq_len, args.pred_len, args.max_stocks) | |
| val = SimplePriceDataset(DATA_DIR, 'val', args.seq_len, args.pred_len, args.max_stocks) | |
| test = SimplePriceDataset(DATA_DIR, 'test', args.seq_len, args.pred_len, args.max_stocks) | |
| train_loader = DataLoader(train, args.batch_size, shuffle=True, num_workers=2, pin_memory=True) | |
| val_loader = DataLoader(val, args.batch_size, shuffle=False, num_workers=1) | |
| test_loader = DataLoader(test, args.batch_size, shuffle=False, num_workers=1) | |
| print(f"Data: train={len(train)} | val={len(val)} | test={len(test)}\n") | |
| # ========== Model Initialization ========== | |
| model = GRUBaseline(Cfg()).cuda() | |
| optimizer = optim.Adam(model.parameters(), lr=args.lr) | |
| # Standard MSE loss (no directional component for baseline) | |
| criterion = nn.MSELoss() | |
| os.makedirs('./results/v4', exist_ok=True) | |
| best_mape = float('inf') | |
| patience_counter = 0 | |
| # ========== Training Loop ========== | |
| for epoch in range(1, args.epochs + 1): | |
| # Training phase | |
| model.train() | |
| train_losses = [] | |
| total = len(train_loader) | |
| for batch_idx, (bx, by) in enumerate(train_loader): | |
| optimizer.zero_grad() | |
| pred = model(bx.cuda())[:, :, 3] | |
| loss = criterion(pred, by.cuda()) | |
| loss.backward() | |
| optimizer.step() | |
| train_losses.append(loss.item()) | |
| # Progress bar (update every 1%) | |
| pct = (batch_idx + 1) / total * 100 | |
| if int(pct) != int(batch_idx / total * 100) or batch_idx == total - 1: | |
| bar_len = int(pct / 5) | |
| bar = '█' * bar_len + '░' * (20 - bar_len) | |
| print(f"\rEpoch {epoch}/{args.epochs}: [{bar}] {pct:.0f}% | loss={loss.item():.4f}", end='', flush=True) | |
| print(f"\rEpoch {epoch}/{args.epochs}: Training done | avg_MSE={np.mean(train_losses):.4f} ") | |
| # Validation phase | |
| model.eval() | |
| vp, vt = [], [] | |
| with torch.no_grad(): | |
| for bx, by in val_loader: | |
| vp.append(model(bx.cuda())[:,:,3]) | |
| vt.append(by.cuda()) | |
| vp = torch.cat(vp).cpu().numpy() | |
| vt = torch.cat(vt).cpu().numpy() | |
| # Compute metrics | |
| val_mse = np.mean((vp-vt)**2) | |
| val_mape = np.mean(np.abs((vp-vt)/(vt+1e-8))) * 100 | |
| val_direction = np.mean((np.sign(vp[:,-1]-vp[:,0]) == np.sign(vt[:,-1]-vt[:,0])).astype(float)) * 100 | |
| print(f" Val MSE={val_mse:.4f} MAPE={val_mape:.2f}% Dir={val_direction:.1f}%", end='') | |
| # Early Stopping | |
| if val_mape < best_mape: | |
| best_mape = val_mape | |
| torch.save(model.state_dict(), f'./results/v4/gru_pred{args.pred_len}.pth') | |
| print(f" [SAVED]") | |
| patience_counter = 0 | |
| else: | |
| patience_counter += 1 | |
| print(f" [patience {patience_counter}/{args.patience}]") | |
| if patience_counter >= args.patience: | |
| print(f"Early Stopping: Val MAPE no improvement for {args.patience} epochs\n") | |
| break | |
| # ========== Test Set Evaluation ========== | |
| print(f"\nEvaluating on test set...", end='', flush=True) | |
| model.load_state_dict(torch.load(f'./results/v4/gru_pred{args.pred_len}.pth')) | |
| model.eval() | |
| tp, tt = [], [] | |
| with torch.no_grad(): | |
| for bx, by in test_loader: | |
| tp.append(model(bx.cuda())[:,:,3]) | |
| tt.append(by.cuda()) | |
| tp = torch.cat(tp).cpu().numpy() | |
| tt = torch.cat(tt).cpu().numpy() | |
| test_mse = np.mean((tp-tt)**2) | |
| test_mape = np.mean(np.abs((tp-tt)/(tt+1e-8))) * 100 | |
| test_direction = np.mean((np.sign(tp[:,-1]-tp[:,0]) == np.sign(tt[:,-1]-tt[:,0])).astype(float)) * 100 | |
| test_ic = np.corrcoef(tp.flatten(), tt.flatten())[0,1] | |
| # Calculate F1 | |
| pred_up = (tp[:,-1] - tp[:,0]) > 0 | |
| true_up = (tt[:,-1] - tt[:,0]) > 0 | |
| tp_count = np.sum(pred_up & true_up) | |
| fp_count = np.sum(pred_up & ~true_up) | |
| fn_count = np.sum(~pred_up & true_up) | |
| precision = tp_count / (tp_count + fp_count + 1e-8) | |
| recall = tp_count / (tp_count + fn_count + 1e-8) | |
| test_f1 = 2 * precision * recall / (precision + recall + 1e-8) * 100 | |
| print(f" MSE={test_mse:.4f} MAPE={test_mape:.2f}% Dir={test_direction:.1f}% F1={test_f1:.1f}% IC={test_ic:.3f}") | |
| print(f"Training complete! Model: ./results/v4/gru_pred{args.pred_len}.pth | Best val MAPE={best_mape:.2f}%\n") | |