Download fin-mm/code/expand_paired_dataset.py from GoldenGrapeGentleman1/FinMM-code: direct link, hf CLI and curl.
- Browser
- Download file 7.01 kB
-
https://huggingface.co/GoldenGrapeGentleman1/FinMM-code/resolve/main/fin-mm/code/expand_paired_dataset.py
- Command line
-
hf download hf://GoldenGrapeGentleman1/FinMM-code/fin-mm/code/expand_paired_dataset.py
-
curl -L -o expand_paired_dataset.py https://huggingface.co/GoldenGrapeGentleman1/FinMM-code/resolve/main/fin-mm/code/expand_paired_dataset.py
7.01 kB
| """ | |
| 扩展配对数据集脚本 | |
| 目标: 从3,033样本扩展到约10,000样本 | |
| 方法: | |
| 1. 扩展时间范围: 2010-2025 (从2018扩展到2010) | |
| 2. 减小滑动步长: 5天 → 3天 | |
| 3. 保持7只股票不变 | |
| 使用: | |
| cd /workspace/Finance/fin-mm | |
| python code/expand_paired_dataset.py | |
| """ | |
| import os | |
| import json | |
| import pandas as pd | |
| import numpy as np | |
| from datetime import datetime, timedelta | |
| from pathlib import Path | |
| import mplfinance as mpf | |
| from PIL import Image | |
| import warnings | |
| warnings.filterwarnings('ignore') | |
| # 配置 | |
| CONFIG = { | |
| 'input_days': 96, # 输入窗口 | |
| 'pred_days': 20, # 预测窗口 | |
| 'stride': 3, # 滑动步长(从5减到3) | |
| 'train_end': '2023-06-30', | |
| 'val_end': '2024-06-30', | |
| 'tickers': ['SPY', 'AAPL', 'MSFT', 'GOOGL', 'AMZN', 'TSLA', 'NVDA', 'META', 'BTC-USD', 'ETH-USD'], # 扩展到10只 | |
| 'data_start': '2010-01-01', # 扩展起始时间 | |
| 'data_end': '2025-12-31', | |
| } | |
| # 路径 | |
| BASE_DIR = Path('/workspace/Finance/fin-mm' if os.path.exists('/workspace') else '/home/amd/yueyuan/Finance/fin-mm') | |
| DATA_DIR = BASE_DIR / 'data' | |
| YAHOO_DIR = DATA_DIR / 'yahoo' | |
| OUTPUT_DIR = DATA_DIR / 'paired_dataset_v2' # 新的输出目录 | |
| def load_yahoo_data(ticker): | |
| """加载Yahoo数据""" | |
| csv_path = YAHOO_DIR / f'{ticker}_1d.csv' | |
| if not csv_path.exists(): | |
| print(f" ⚠️ {ticker} 数据不存在,跳过") | |
| return None | |
| df = pd.read_csv(csv_path, parse_dates=['Date']) | |
| df = df.sort_values('Date').reset_index(drop=True) | |
| # 确保有足够的数据 | |
| df = df[df['Date'] >= CONFIG['data_start']] | |
| print(f" {ticker}: {len(df)} 天数据 ({df['Date'].min().date()} ~ {df['Date'].max().date()})") | |
| return df | |
| def generate_kline_image(df_window, output_path): | |
| """生成K线图PNG""" | |
| df_plot = df_window.copy() | |
| df_plot.set_index('Date', inplace=True) | |
| # K线图样式 | |
| style = mpf.make_mpf_style( | |
| base_mpf_style='charles', | |
| rc={'font.size': 8} | |
| ) | |
| # 保存K线图 | |
| mpf.plot( | |
| df_plot, | |
| type='candle', | |
| volume=True, | |
| style=style, | |
| savefig=dict(fname=str(output_path), dpi=100, bbox_inches='tight'), | |
| figsize=(12, 6) | |
| ) | |
| def generate_samples(ticker, df, split, output_base): | |
| """为单个股票生成样本""" | |
| samples = [] | |
| # 确定时间范围 | |
| if split == 'train': | |
| df_split = df[df['Date'] <= CONFIG['train_end']] | |
| elif split == 'val': | |
| df_split = df[(df['Date'] > CONFIG['train_end']) & (df['Date'] <= CONFIG['val_end'])] | |
| else: # test | |
| df_split = df[df['Date'] > CONFIG['val_end']] | |
| if len(df_split) < CONFIG['input_days'] + CONFIG['pred_days']: | |
| return samples | |
| # 创建输出目录 | |
| ts_dir = output_base / split / 'timeseries' | |
| img_dir = output_base / split / 'kline_img' | |
| ts_dir.mkdir(parents=True, exist_ok=True) | |
| img_dir.mkdir(parents=True, exist_ok=True) | |
| # 滑动窗口生成样本 | |
| total_days = len(df_split) | |
| window_size = CONFIG['input_days'] + CONFIG['pred_days'] | |
| for start_idx in range(0, total_days - window_size + 1, CONFIG['stride']): | |
| end_idx = start_idx + window_size | |
| window = df_split.iloc[start_idx:end_idx].reset_index(drop=True) | |
| input_window = window.iloc[:CONFIG['input_days']] | |
| target_window = window.iloc[CONFIG['input_days']:] | |
| # 样本ID | |
| start_date = input_window['Date'].iloc[0].strftime('%Y%m%d') | |
| end_date = input_window['Date'].iloc[-1].strftime('%Y%m%d') | |
| sample_id = f"{ticker}_{start_date}_{end_date}" | |
| # 保存时序CSV | |
| csv_path = ts_dir / f"{sample_id}.csv" | |
| input_window.to_csv(csv_path, index=False) | |
| # 生成K线图 | |
| png_path = img_dir / f"{sample_id}.png" | |
| try: | |
| generate_kline_image(input_window, png_path) | |
| except Exception as e: | |
| # 如果生成失败,创建空白图 | |
| img = Image.new('RGB', (1200, 600), color='white') | |
| img.save(png_path) | |
| # 样本元数据 | |
| sample = { | |
| 'sample_id': sample_id, | |
| 'ticker': ticker, | |
| 'split': split, | |
| 'input_start': input_window['Date'].iloc[0].strftime('%Y-%m-%d'), | |
| 'input_end': input_window['Date'].iloc[-1].strftime('%Y-%m-%d'), | |
| 'input_days': CONFIG['input_days'], | |
| 'target_start': target_window['Date'].iloc[0].strftime('%Y-%m-%d'), | |
| 'target_end': target_window['Date'].iloc[-1].strftime('%Y-%m-%d'), | |
| 'target_days': CONFIG['pred_days'], | |
| 'target_close': [float(x) for x in target_window['Close'].tolist()], # 确保是float | |
| 'csv_path': f"{split}/timeseries/{sample_id}.csv", | |
| 'png_path': f"{split}/kline_img/{sample_id}.png" | |
| } | |
| samples.append(sample) | |
| return samples | |
| def main(): | |
| print("=" * 70) | |
| print("扩展配对数据集") | |
| print(f"目标: 从3,033样本扩展到约10,000样本") | |
| print(f"方法: 滑动步长 5→3, 时间范围扩展") | |
| print("=" * 70) | |
| # 创建输出目录 | |
| OUTPUT_DIR.mkdir(parents=True, exist_ok=True) | |
| # 加载所有股票数据 | |
| print("\n📊 加载Yahoo数据...") | |
| stock_data = {} | |
| for ticker in CONFIG['tickers']: | |
| df = load_yahoo_data(ticker) | |
| if df is not None: | |
| stock_data[ticker] = df | |
| # 生成样本 | |
| all_samples = {'train': [], 'val': [], 'test': []} | |
| print("\n🔧 生成配对样本...") | |
| for ticker, df in stock_data.items(): | |
| print(f"\n处理 {ticker}...") | |
| for split in ['train', 'val', 'test']: | |
| samples = generate_samples(ticker, df, split, OUTPUT_DIR) | |
| all_samples[split].extend(samples) | |
| print(f" {split}: {len(samples)} 样本") | |
| # 保存manifest | |
| manifest = { | |
| 'config': CONFIG, | |
| 'created': datetime.now().strftime('%Y-%m-%d %H:%M:%S'), | |
| 'splits': all_samples | |
| } | |
| manifest_path = OUTPUT_DIR / 'manifest_pred20.json' | |
| with open(manifest_path, 'w') as f: | |
| json.dump(manifest, f, indent=2) | |
| # 保存各split的samples文件(兼容旧版dataset_paired.py) | |
| for split in ['train', 'val', 'test']: | |
| split_dir = OUTPUT_DIR / split | |
| samples_file = split_dir / 'samples_pred20.json' | |
| with open(samples_file, 'w') as f: | |
| json.dump(all_samples[split], f, indent=2) | |
| print(f"✅ {split} samples保存: {samples_file}") | |
| # 统计 | |
| print("\n" + "=" * 70) | |
| print("📊 生成统计") | |
| print("=" * 70) | |
| total = 0 | |
| for split in ['train', 'val', 'test']: | |
| count = len(all_samples[split]) | |
| total += count | |
| print(f"{split:8s}: {count:6d} 样本") | |
| print(f"{'总计':8s}: {total:6d} 样本") | |
| print(f"\n✅ Manifest保存: {manifest_path}") | |
| print("=" * 70) | |
| if __name__ == '__main__': | |
| main() | |