Download src/datasets/dataset_with_kline.py from GoldenGrapeGentleman1/FinMM-Project-FinMM: direct link, hf CLI and curl.
- Browser
- Download file 4.77 kB
-
https://huggingface.co/GoldenGrapeGentleman1/FinMM-Project-FinMM/resolve/main/src/datasets/dataset_with_kline.py
- Command line
-
hf download hf://GoldenGrapeGentleman1/FinMM-Project-FinMM/src/datasets/dataset_with_kline.py
-
curl -L -o dataset_with_kline.py https://huggingface.co/GoldenGrapeGentleman1/FinMM-Project-FinMM/resolve/main/src/datasets/dataset_with_kline.py
4.77 kB
| """ | |
| 包含K线图的数据集(时序+图像) | |
| 匹配96天时序数据与对应半年K线图 | |
| """ | |
| import os, json | |
| import pandas as pd | |
| import numpy as np | |
| import torch | |
| from torch.utils.data import Dataset | |
| from PIL import Image | |
| from datetime import datetime | |
| class TimeSeriesWithKlineDataset(Dataset): | |
| """时序数据 + K线图""" | |
| def __init__(self, index_file, mode='train', seq_len=96, pred_len=20, max_stocks=100): | |
| self.seq_len = seq_len | |
| self.samples = [] | |
| # 时间划分 | |
| 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') | |
| # 读取index(股票→K线图映射) | |
| with open(index_file) as f: | |
| index_data = [json.loads(line) for line in f] | |
| stock_count = 0 | |
| loaded_count = 0 | |
| for stock_info in index_data: | |
| if stock_count >= max_stocks: | |
| break | |
| loaded_count += 1 | |
| # 只用HS300(有K线图) | |
| if stock_info['market'] != 'HS300': | |
| continue | |
| if loaded_count % 100 == 0: | |
| print(f" 已扫描{loaded_count}只,加载{stock_count}只", flush=True) | |
| stock_id = stock_info['stock_id'] | |
| # 容器内路径映射 | |
| ts_file = stock_info['time_series_files'][0].replace('/workspace/data', '/workspace/Finance/fin-mm/data') | |
| # 读取时序数据 | |
| try: | |
| df = pd.read_csv(ts_file) | |
| if len(df) < 4000: # 降低阈值:4000天≈16年 | |
| continue | |
| df['Date'] = pd.to_datetime(df['Date'], utc=True).dt.tz_convert(None) | |
| df_filtered = df[(df['Date'] >= start) & (df['Date'] <= end)] | |
| if len(df_filtered) < seq_len + pred_len: | |
| continue | |
| # 构建K线图映射(日期→图片路径) | |
| kline_map = {} | |
| for img_path in stock_info['image_files']: | |
| # 解析:stock_id_YYYY_HX_candlestick.png | |
| basename = os.path.basename(img_path) | |
| year_half = basename.split('_')[1:3] # ['2023', 'H1'] | |
| kline_map[tuple(year_half)] = img_path.replace('/workspace/data', '/workspace/Finance/fin-mm/data') | |
| # log变换 | |
| data_log = np.log(df_filtered[['Open', 'High', 'Low', 'Close', 'Volume']].values + 1) | |
| # 滑动窗口 + 匹配K线图 | |
| for i in range(len(data_log) - seq_len - pred_len): | |
| # 获取当前样本的日期 | |
| sample_end_date = df_filtered.iloc[i + seq_len - 1]['Date'] | |
| year = sample_end_date.year | |
| half = 'H1' if sample_end_date.month <= 6 else 'H2' | |
| # 查找对应K线图 | |
| kline_key = (str(year), half) | |
| if kline_key in kline_map and os.path.exists(kline_map[kline_key]): | |
| self.samples.append({ | |
| 'ts_data': data_log[i:i+seq_len+pred_len], | |
| 'kline_path': kline_map[kline_key], | |
| 'stock_id': stock_id | |
| }) | |
| stock_count += 1 | |
| except Exception as e: | |
| continue | |
| print(f"{mode}: {len(self.samples)}样本 ({stock_count}只股票,含K线图)") | |
| def __len__(self): | |
| return len(self.samples) | |
| def __getitem__(self, idx): | |
| sample = self.samples[idx] | |
| ts_data = sample['ts_data'] | |
| # 时序数据 | |
| x = torch.FloatTensor(ts_data[:self.seq_len]) # [96, 5] | |
| y = torch.FloatTensor(ts_data[self.seq_len:, 3]) # [20] | |
| # K线图(RGB图像,resize到336x336 - 匹配LLaVA-plus) | |
| try: | |
| img = Image.open(sample['kline_path']).convert('RGB') | |
| img = img.resize((336, 336)) # LLaVA用CLIP-336版本 | |
| img_tensor = torch.FloatTensor(np.array(img)).permute(2, 0, 1) / 255.0 # [3, 336, 336] | |
| except: | |
| # 如果图片加载失败,用零图 | |
| img_tensor = torch.zeros(3, 336, 336) | |
| return { | |
| 'ts': x, | |
| 'image': img_tensor, | |
| 'target': y | |
| } | |