File size: 7,723 Bytes
3621f16 | 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 | """
Training: Linear pred20 (Full parameterized version).
Usage: python train_linear_pred20.py --max_stocks 2 --epochs 1 --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='Linear Time Series Prediction Training')
parser.add_argument('--max_stocks', type=int, default=300, help='Max number of stocks')
parser.add_argument('--epochs', type=int, default=30, help='Max training epochs')
parser.add_argument('--batch_size', type=int, default=32, help='Batch size')
parser.add_argument('--lr', type=float, default=1e-4, 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"\nLinear 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_linear import LinearBaseline
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 = LinearBaseline(Cfg()).cuda()
optimizer = optim.Adam(model.parameters(), lr=args.lr)
os.makedirs('./results/v2', 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 = nn.MSELoss()(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} ")
train_mse = np.mean(train_losses)
# Validation phase (every 5 epochs or last epoch)
if epoch % 5 == 0 or epoch == args.epochs:
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/v2/linear_pred{args.pred_len}.pth')
print(f" [SAVED]")
patience_counter = 0
else:
patience_counter += 1
print(f" [patience {patience_counter}/{args.patience}]")
# Early Stopping
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/v2/linear_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]
print(f" MSE={test_mse:.4f} MAPE={test_mape:.2f}% Dir={test_direction:.1f}% IC={test_ic:.3f}")
print(f"Training complete! Model: ./results/v2/linear_pred{args.pred_len}.pth | Best val MAPE={best_mape:.2f}%\n")
|