FinMM-code / fin-mm /code /dataset_paired.py
GoldenGrapeGentleman1's picture
Upload fin-mm/code (part 2)
43235e7 verified
Raw History Blame Contribute Delete
8.37 kB
"""
Paired Dataset Loader for Multi-Modal Training.
Loads the paired (CSV + PNG) dataset generated by generate_paired_dataset.py.
Compatible with LLaVA+DMMV-A+DMMV-S+Kronos training pipeline.
Output format matches TimeSeriesWithKlineDataset:
- ts: [seq_len, 5] OHLCV time series (log-transformed)
- image: [3, 336, 336] K-line chart image
- target: [pred_len] Close prices (log-transformed)
"""
import os
import json
import pandas as pd
import numpy as np
import torch
from torch.utils.data import Dataset
from PIL import Image
from pathlib import Path
class PairedDataset(Dataset):
"""
Load paired time series CSV and K-line PNG for multi-modal training.
Expects directory structure:
data_dir/
+-- train/
| +-- timeseries/*.csv
| +-- kline_img/*.png
| +-- samples_pred20.json
+-- val/
+-- test/
"""
def __init__(
self,
data_dir: str,
mode: str = 'train',
seq_len: int = 96,
pred_len: int = 20,
max_samples: int = None,
use_log_transform: bool = True,
exclude_tickers: list = None,
include_only: list = None
):
"""
Args:
data_dir: Path to paired_dataset directory
mode: 'train', 'val', or 'test'
seq_len: Input sequence length (should match CSV data)
pred_len: Prediction length
max_samples: Limit number of samples (for quick testing)
use_log_transform: Apply log(x+1) transform to prices
exclude_tickers: List of tickers to exclude (e.g., ['BTC-USD', 'ETH-USD'])
include_only: List of tickers to include only (e.g., ['BTC-USD', 'ETH-USD'])
"""
self.data_dir = Path(data_dir)
self.mode = mode
self.seq_len = seq_len
self.pred_len = pred_len
self.use_log_transform = use_log_transform
self.exclude_tickers = exclude_tickers or []
self.include_only = include_only or []
# Load sample index
samples_file = self.data_dir / mode / f"samples_pred{pred_len}.json"
if not samples_file.exists():
raise FileNotFoundError(f"Samples file not found: {samples_file}")
with open(samples_file, 'r') as f:
all_samples = json.load(f)
# 过滤数据
if self.include_only:
self.samples = [s for s in all_samples if s['ticker'] in self.include_only]
print(f"[PairedDataset] {mode}: {len(self.samples)} samples (仅包含{self.include_only})")
elif self.exclude_tickers:
self.samples = [s for s in all_samples if s['ticker'] not in self.exclude_tickers]
print(f"[PairedDataset] {mode}: {len(self.samples)} samples (排除{self.exclude_tickers})")
else:
self.samples = all_samples
print(f"[PairedDataset] {mode}: {len(self.samples)} samples loaded")
# Limit samples if requested
if max_samples is not None:
self.samples = self.samples[:max_samples]
def __len__(self):
return len(self.samples)
def __getitem__(self, idx):
sample = self.samples[idx]
# Load time series CSV
csv_path = self.data_dir / sample['csv_path']
df = pd.read_csv(csv_path)
# Extract OHLCV data
ohlcv = df[['Open', 'High', 'Low', 'Close', 'Volume']].values
# Apply log transform (standard practice for financial data)
if self.use_log_transform:
ohlcv = np.log(ohlcv + 1)
# Get target from sample info (already stored in manifest)
target = np.array(sample['target_close'])
if self.use_log_transform:
target = np.log(target + 1)
# Load K-line image
png_path = self.data_dir / sample['png_path']
try:
img = Image.open(png_path).convert('RGB')
img = img.resize((336, 336)) # LLaVA CLIP-336
img_tensor = torch.FloatTensor(np.array(img)).permute(2, 0, 1) / 255.0
except Exception as e:
print(f"Warning: Failed to load image {png_path}: {e}")
img_tensor = torch.zeros(3, 336, 336)
return {
'ts': torch.FloatTensor(ohlcv), # [96, 5]
'image': img_tensor, # [3, 336, 336]
'target': torch.FloatTensor(target), # [20]
'sample_id': sample['sample_id'] # For debugging
}
class PairedDatasetSimple(Dataset):
"""
Simplified version without K-line images.
For testing DMMV/Kronos models without LLaVA.
"""
def __init__(
self,
data_dir: str,
mode: str = 'train',
seq_len: int = 96,
pred_len: int = 20,
max_samples: int = None,
use_log_transform: bool = True
):
self.data_dir = Path(data_dir)
self.mode = mode
self.seq_len = seq_len
self.pred_len = pred_len
self.use_log_transform = use_log_transform
samples_file = self.data_dir / mode / f"samples_pred{pred_len}.json"
if not samples_file.exists():
raise FileNotFoundError(f"Samples file not found: {samples_file}")
with open(samples_file, 'r') as f:
self.samples = json.load(f)
if max_samples is not None:
self.samples = self.samples[:max_samples]
print(f"[PairedDatasetSimple] {mode}: {len(self.samples)} samples")
def __len__(self):
return len(self.samples)
def __getitem__(self, idx):
sample = self.samples[idx]
csv_path = self.data_dir / sample['csv_path']
df = pd.read_csv(csv_path)
ohlcv = df[['Open', 'High', 'Low', 'Close', 'Volume']].values
if self.use_log_transform:
ohlcv = np.log(ohlcv + 1)
target = np.array(sample['target_close'])
if self.use_log_transform:
target = np.log(target + 1)
return torch.FloatTensor(ohlcv), torch.FloatTensor(target)
def test_dataset():
"""Quick test to verify dataset loading works."""
import sys
# Use relative path for testing
data_dir = Path(__file__).parent.parent / "data" / "paired_dataset"
if not data_dir.exists():
print(f"[ERROR] Data directory not found: {data_dir}")
print("Please run generate_paired_dataset.py first.")
return False
print("=" * 60)
print("Testing PairedDataset Loading")
print("=" * 60)
success = True
for mode in ['train', 'val', 'test']:
try:
ds = PairedDataset(data_dir, mode=mode, max_samples=5)
if len(ds) == 0:
print(f"[WARN] {mode}: No samples")
continue
sample = ds[0]
print(f"\n[{mode}] First sample:")
print(f" sample_id: {sample['sample_id']}")
print(f" ts shape: {sample['ts'].shape}")
print(f" image shape: {sample['image'].shape}")
print(f" target shape: {sample['target'].shape}")
# Verify shapes
assert sample['ts'].shape == (96, 5), f"Expected ts shape (96, 5), got {sample['ts'].shape}"
assert sample['image'].shape == (3, 336, 336), f"Expected image shape (3, 336, 336), got {sample['image'].shape}"
assert sample['target'].shape[0] == 20, f"Expected target length 20, got {sample['target'].shape[0]}"
print(f" [OK] Shapes verified!")
except Exception as e:
print(f"[ERROR] {mode}: {e}")
success = False
print("\n" + "=" * 60)
if success:
print("[SUCCESS] Dataset loading verified!")
else:
print("[FAILED] Some tests failed")
print("=" * 60)
return success
if __name__ == "__main__":
test_dataset()