FinMM-code / fin-mm /code /generate_paired_dataset.py
GoldenGrapeGentleman1's picture
Upload fin-mm/code (part 2)
43235e7 verified
Raw History Blame Contribute Delete
14 kB
"""
Paired Dataset Generator for Multi-Modal Financial Time Series Prediction.
Generates paired (time_series_csv, kline_image_png) samples that are
precisely aligned for LLaVA + DMMV multi-modal fusion training.
Key Guarantee:
- Each sample has EXACTLY matched time window between CSV and PNG
- Filename encodes the exact date range for verification
- Sample ID enables 1:1 correspondence during training
Data Structure per Sample:
sample_id: AAPL_20180102_20180420
β”œβ”€β”€ timeseries/AAPL_20180102_20180420.csv (96 days OHLCV input)
β”œβ”€β”€ kline_img/AAPL_20180102_20180420.png (96 days candlestick)
└── target: next 20 days Close prices
Prediction Tasks:
- pred5: 96d input -> 5d prediction
- pred20: 96d input -> 20d prediction
- pred60: 120d input -> 60d prediction
"""
import pandas as pd
from pathlib import Path
from datetime import datetime
import json
import argparse
import warnings
warnings.filterwarnings('ignore')
# Lazy import matplotlib (only when generating images)
plt = None
Rectangle = None
def _import_matplotlib():
global plt, Rectangle
if plt is None:
import matplotlib.pyplot as _plt
from matplotlib.patches import Rectangle as _Rectangle
plt = _plt
Rectangle = _Rectangle
# =============================================================================
# Configuration
# =============================================================================
# Input/Output directories
DATA_DIR = Path("data/yahoo")
OUTPUT_DIR = Path("data/paired_dataset")
# Image settings (LLaVA ViT-L/14-336)
FIGSIZE = (3.36, 3.36)
DPI = 100 # 336x336 pixels
# Prediction task configurations
TASKS = {
"pred5": {"input_days": 96, "pred_days": 5},
"pred10": {"input_days": 96, "pred_days": 10},
"pred20": {"input_days": 96, "pred_days": 20},
"pred60": {"input_days": 120, "pred_days": 60},
}
# Default settings
DEFAULT_TASK = "pred20"
DEFAULT_STRIDE = 5
# Chart colors
COLORS = {
'up': '#26A69A',
'down': '#EF5350',
'background': 'white',
}
# =============================================================================
# Candlestick Drawing
# =============================================================================
def draw_candlestick(ax, df: pd.DataFrame):
"""Draw candlestick chart on axes."""
_import_matplotlib()
width = 0.6
for idx in range(len(df)):
row = df.iloc[idx]
o, h, l, c = row['Open'], row['High'], row['Low'], row['Close']
color = COLORS['up'] if c >= o else COLORS['down']
bottom = min(o, c)
height = abs(c - o)
# Candle body
rect = Rectangle((idx - width/2, bottom), width, height,
facecolor=color, edgecolor=color, linewidth=0.5)
ax.add_patch(rect)
# Wicks
ax.plot([idx, idx], [l, h], color=color, linewidth=0.8)
ax.set_xlim(-1, len(df))
y_min, y_max = df['Low'].min(), df['High'].max()
y_range = y_max - y_min
ax.set_ylim(y_min - 0.05 * y_range, y_max + 0.05 * y_range)
def generate_kline_image(df: pd.DataFrame, output_path: Path) -> bool:
"""Generate candlestick image from OHLCV data."""
_import_matplotlib()
try:
fig, ax = plt.subplots(1, 1, figsize=FIGSIZE)
fig.patch.set_facecolor(COLORS['background'])
ax.set_facecolor(COLORS['background'])
draw_candlestick(ax, df)
# Clean style
ax.set_xticks([])
ax.set_yticks([])
for spine in ax.spines.values():
spine.set_visible(False)
ax.grid(True, alpha=0.2)
plt.tight_layout(pad=0.1)
fig.savefig(output_path, dpi=DPI, bbox_inches='tight',
pad_inches=0.02, facecolor=COLORS['background'])
plt.close(fig)
return True
except Exception as e:
plt.close('all')
return False
# =============================================================================
# Paired Dataset Generation
# =============================================================================
def generate_paired_samples(
ticker: str,
task: str = DEFAULT_TASK,
stride: int = DEFAULT_STRIDE,
split_ratios: dict = None
) -> dict:
"""
Generate paired (CSV, PNG) samples for a ticker.
Args:
ticker: Stock/crypto symbol
task: Prediction task name (pred5, pred20, pred60)
stride: Days between samples
split_ratios: Train/val/test split dates
Returns:
Dictionary with sample counts per split
"""
if split_ratios is None:
split_ratios = {
'train': ('2018-01-01', '2022-12-31'),
'val': ('2023-01-01', '2023-12-31'),
'test': ('2024-01-01', '2026-12-31'),
}
# Load data
data_path = DATA_DIR / f"{ticker}_1d.csv"
if not data_path.exists():
print(f" [ERROR] Data not found: {data_path}")
return {}
df = pd.read_csv(data_path)
df['Date'] = pd.to_datetime(df['Date'])
# Get task config
task_config = TASKS.get(task, TASKS[DEFAULT_TASK])
input_days = task_config['input_days']
pred_days = task_config['pred_days']
window_size = input_days + pred_days
# Create output directories
for split in ['train', 'val', 'test']:
(OUTPUT_DIR / split / "timeseries").mkdir(parents=True, exist_ok=True)
(OUTPUT_DIR / split / "kline_img").mkdir(parents=True, exist_ok=True)
# Track samples
sample_counts = {'train': 0, 'val': 0, 'test': 0}
sample_index = [] # For manifest file
# Generate samples with sliding window
for i in range(0, len(df) - window_size + 1, stride):
# Extract window
input_df = df.iloc[i:i + input_days].copy()
target_df = df.iloc[i + input_days:i + window_size].copy()
# Get date range
start_date = input_df['Date'].iloc[0]
end_date = input_df['Date'].iloc[-1]
# Determine split based on END date of input window
split = None
for split_name, (split_start, split_end) in split_ratios.items():
if pd.to_datetime(split_start) <= end_date <= pd.to_datetime(split_end):
split = split_name
break
if split is None:
continue
# Create sample ID
start_str = start_date.strftime('%Y%m%d')
end_str = end_date.strftime('%Y%m%d')
sample_id = f"{ticker}_{start_str}_{end_str}"
# Output paths
csv_path = OUTPUT_DIR / split / "timeseries" / f"{sample_id}.csv"
png_path = OUTPUT_DIR / split / "kline_img" / f"{sample_id}.png"
# Check if already exists
already_exists = csv_path.exists() and png_path.exists()
if not already_exists:
# Save time series CSV (input window only)
input_df_save = input_df[['Date', 'Open', 'High', 'Low', 'Close', 'Volume']].copy()
input_df_save['Date'] = input_df_save['Date'].dt.strftime('%Y-%m-%d')
input_df_save.to_csv(csv_path, index=False)
# Generate K-line image
if not generate_kline_image(input_df, png_path):
continue
# Record sample info (always, even if files existed)
sample_info = {
'sample_id': sample_id,
'ticker': ticker,
'split': split,
'input_start': start_date.strftime('%Y-%m-%d'),
'input_end': end_date.strftime('%Y-%m-%d'),
'input_days': input_days,
'target_start': target_df['Date'].iloc[0].strftime('%Y-%m-%d'),
'target_end': target_df['Date'].iloc[-1].strftime('%Y-%m-%d'),
'target_days': pred_days,
'target_close': target_df['Close'].tolist(),
'csv_path': str(csv_path.relative_to(OUTPUT_DIR)),
'png_path': str(png_path.relative_to(OUTPUT_DIR)),
}
sample_index.append(sample_info)
sample_counts[split] += 1
return sample_counts, sample_index
def save_manifest(all_samples: list, task: str):
"""Save manifest file with all sample information."""
manifest = {
'task': task,
'task_config': TASKS[task],
'created': datetime.now().isoformat(),
'total_samples': len(all_samples),
'splits': {
'train': [s for s in all_samples if s['split'] == 'train'],
'val': [s for s in all_samples if s['split'] == 'val'],
'test': [s for s in all_samples if s['split'] == 'test'],
}
}
# Save full manifest
manifest_path = OUTPUT_DIR / f"manifest_{task}.json"
with open(manifest_path, 'w') as f:
json.dump(manifest, f, indent=2)
# Save split-specific files for easy loading
for split in ['train', 'val', 'test']:
split_samples = manifest['splits'][split]
split_path = OUTPUT_DIR / split / f"samples_{task}.json"
with open(split_path, 'w') as f:
json.dump(split_samples, f, indent=2)
print(f"\nManifest saved: {manifest_path}")
return manifest
# =============================================================================
# Main Entry Point
# =============================================================================
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Generate paired (CSV, PNG) dataset for multi-modal training"
)
parser.add_argument(
'--tickers', nargs='+',
default=['SPY', 'AAPL', 'MSFT', 'GOOGL', 'AMZN', 'BTC-USD', 'ETH-USD'],
help='Ticker symbols to process'
)
parser.add_argument(
'--task', choices=['pred5', 'pred10', 'pred20', 'pred60'], default=DEFAULT_TASK,
help=f'Prediction task (default: {DEFAULT_TASK})'
)
parser.add_argument(
'--stride', type=int, default=DEFAULT_STRIDE,
help=f'Days between samples (default: {DEFAULT_STRIDE})'
)
parser.add_argument(
'--estimate-only', action='store_true',
help='Only estimate, do not generate'
)
args = parser.parse_args()
task_config = TASKS[args.task]
print("=" * 70)
print("Paired Dataset Generator (Time Series CSV + K-line PNG)")
print("=" * 70)
print(f"Task: {args.task}")
print(f" - Input window: {task_config['input_days']} days")
print(f" - Prediction: {task_config['pred_days']} days")
print(f"Stride: {args.stride} days")
print(f"Tickers: {args.tickers}")
print(f"Output: {OUTPUT_DIR.absolute()}")
print("=" * 70)
# Estimate storage
print("\nEstimated samples per ticker:")
total_estimate = 0
for ticker in args.tickers:
data_path = DATA_DIR / f"{ticker}_1d.csv"
if data_path.exists():
df = pd.read_csv(data_path)
window = task_config['input_days'] + task_config['pred_days']
samples = max(0, (len(df) - window) // args.stride + 1)
print(f" {ticker}: ~{samples} samples")
total_estimate += samples
csv_size = 5 # KB per CSV
png_size = 75 # KB per PNG
total_size_mb = total_estimate * (csv_size + png_size) / 1024
print(f"\nTotal: ~{total_estimate} samples")
print(f"Estimated size: ~{total_size_mb:.1f} MB")
print(" - CSV files: ~{:.1f} MB".format(total_estimate * csv_size / 1024))
print(" - PNG files: ~{:.1f} MB".format(total_estimate * png_size / 1024))
print("=" * 70)
if args.estimate_only:
print("\n[Estimate only - no files generated]")
exit(0)
# Generate paired samples
print("\nGenerating paired samples...")
all_samples = []
total_counts = {'train': 0, 'val': 0, 'test': 0}
for idx, ticker in enumerate(args.tickers):
print(f"\n[{idx+1}/{len(args.tickers)}] Processing {ticker}...")
counts, samples = generate_paired_samples(
ticker=ticker,
task=args.task,
stride=args.stride
)
if counts:
for split, count in counts.items():
total_counts[split] += count
all_samples.extend(samples)
print(f" Train: {counts.get('train', 0)}, "
f"Val: {counts.get('val', 0)}, "
f"Test: {counts.get('test', 0)}")
# Save manifest
manifest = save_manifest(all_samples, args.task)
# Summary
print("\n" + "=" * 70)
print("Generation Complete!")
print("=" * 70)
print(f"\nSample counts:")
print(f" Train: {total_counts['train']}")
print(f" Val: {total_counts['val']}")
print(f" Test: {total_counts['test']}")
print(f" Total: {sum(total_counts.values())}")
print(f"\nOutput structure:")
print(f" {OUTPUT_DIR}/")
print(f" +-- train/")
print(f" | +-- timeseries/ (*.csv)")
print(f" | +-- kline_img/ (*.png)")
print(f" | +-- samples_{args.task}.json")
print(f" +-- val/")
print(f" | +-- ...")
print(f" +-- test/")
print(f" | +-- ...")
print(f" +-- manifest_{args.task}.json")
print("\n" + "=" * 70)
print("ALIGNMENT GUARANTEE:")
print(" Each sample_id (e.g., AAPL_20180102_20180420) has:")
print(" - timeseries/AAPL_20180102_20180420.csv (96 days OHLCV)")
print(" - kline_img/AAPL_20180102_20180420.png (same 96 days chart)")
print(" [OK] Time windows are EXACTLY matched!")
print("=" * 70)