Download fin-mm/code/FinMultiTime_download.py from GoldenGrapeGentleman1/FinMM-code: direct link, hf CLI and curl.
- Browser
- Download file 7.5 kB
-
https://huggingface.co/GoldenGrapeGentleman1/FinMM-code/resolve/main/fin-mm/code/FinMultiTime_download.py
- Command line
-
hf download hf://GoldenGrapeGentleman1/FinMM-code/fin-mm/code/FinMultiTime_download.py
-
curl -L -o FinMultiTime_download.py https://huggingface.co/GoldenGrapeGentleman1/FinMM-code/resolve/main/fin-mm/code/FinMultiTime_download.py
7.5 kB
| from __future__ import annotations | |
| from typing import Dict, Any | |
| from pathlib import Path | |
| import csv | |
| import json | |
| from tqdm import tqdm | |
| from huggingface_hub import snapshot_download | |
| # ========= 全局路径配置 ========= | |
| DATA_ROOT = Path("/workspace/data/finmultitime_hf") # HuggingFace 仓库本地目录 | |
| OUT_STOCK_MODAL_INDEX = Path("/workspace/data/finmultitime_stock_modal_index.jsonl") | |
| OUT_FOUR_MODAL_INDEX = Path("/workspace/data/finmultitime_four_modal_files.jsonl") | |
| # ========= 第一步:下载完整 FinMultiTime 仓库(只在本地不完整时下载) ========= | |
| def repo_already_downloaded() -> bool: | |
| """ | |
| 只有当四个模态目录和两份 *_stock_data_description.csv 都存在时, | |
| 才认为仓库已完整下载。 | |
| """ | |
| if not DATA_ROOT.exists(): | |
| return False | |
| # 四个模态目录都要有 | |
| need_dirs = ["image", "table", "text", "time_series"] | |
| for d in need_dirs: | |
| if not (DATA_ROOT / d).is_dir(): | |
| return False | |
| # 两个描述 CSV 也要有 | |
| if not (DATA_ROOT / "sp500stock_data_description.csv").is_file(): | |
| return False | |
| if not (DATA_ROOT / "hs300stock_data_description.csv").is_file(): | |
| return False | |
| return True | |
| def download_repo_if_needed(): | |
| DATA_ROOT.mkdir(parents=True, exist_ok=True) | |
| if repo_already_downloaded(): | |
| print(f"[FinMultiTime] Repo already complete at {DATA_ROOT}, skip download.") | |
| return | |
| print("[FinMultiTime] Repo not complete locally, start downloading from HF Hub...") | |
| snapshot_download( | |
| repo_id="Wenyan0110/Multimodal-Dataset-Image_Text_Table_TimeSeries-for-Financial-Time-Series-Forecasting", | |
| repo_type="dataset", | |
| local_dir=str(DATA_ROOT), | |
| local_dir_use_symlinks=False, | |
| ) | |
| print(f"[FinMultiTime] Repo downloaded to: {DATA_ROOT}") | |
| # ========= 第二步:解析 *_data_description.csv (股票层面模态标记) ========= | |
| def load_desc(csv_path: Path, market: str) -> Dict[str, Dict[str, Any]]: | |
| """ | |
| 读取 *_stock_data_description.csv,返回: | |
| { stock_id: {market, has_image, has_time_series, has_table, has_text, extra } } | |
| """ | |
| def read_csv_with_encoding(path: Path): | |
| # 先尝试 utf-8,不行再退到 gbk / latin1,解决编码问题 | |
| for enc in ("utf-8", "gbk", "gb2312", "latin1"): | |
| try: | |
| with path.open("r", encoding=enc) as f: | |
| content = f.read() | |
| return content, enc | |
| except UnicodeDecodeError: | |
| continue | |
| raise UnicodeDecodeError(f"Cannot decode {path} with any encoding") | |
| meta: Dict[str, Dict[str, Any]] = {} | |
| content, enc = read_csv_with_encoding(csv_path) | |
| reader = csv.DictReader(content.splitlines()) | |
| for row in reader: | |
| # —— 这里根据实际表头修改 —— # | |
| stock_id = row.get("stock_id") or row.get("ticker") or row.get("symbol") | |
| if not stock_id: | |
| continue | |
| rec: Dict[str, Any] = { | |
| "stock_id": stock_id, | |
| "market": market, | |
| } | |
| # 假设 CSV 里用 0/1 或 True/False 标记四模态,可按真实字段名调整 | |
| def flag(name: str) -> bool: | |
| v = (row.get(name) or "").strip() | |
| return v in ("1", "True", "true", "TRUE", "Y", "y", "Yes", "yes") | |
| # —— 这些字段名要按照 CSV 表头修改 —— # | |
| rec["has_image"] = flag("has_image") | |
| rec["has_time_series"] = flag("has_time_series") | |
| rec["has_table"] = flag("has_table") | |
| rec["has_text"] = flag("has_text") | |
| rec["extra"] = row | |
| meta[stock_id] = rec | |
| return meta | |
| def build_stock_modal_index(): | |
| sp500_desc = DATA_ROOT / "sp500stock_data_description.csv" | |
| hs300_desc = DATA_ROOT / "hs300stock_data_description.csv" | |
| sp500_meta = load_desc(sp500_desc, market="SP500") | |
| hs300_meta = load_desc(hs300_desc, market="HS300") | |
| OUT_STOCK_MODAL_INDEX.parent.mkdir(parents=True, exist_ok=True) | |
| with OUT_STOCK_MODAL_INDEX.open("w", encoding="utf-8") as f: | |
| for d in sp500_meta.values(): | |
| f.write(json.dumps(d, ensure_ascii=False) + "\n") | |
| for d in hs300_meta.values(): | |
| f.write(json.dumps(d, ensure_ascii=False) + "\n") | |
| print(f"[FinMultiTime] Stock-level modal index saved to: {OUT_STOCK_MODAL_INDEX}") | |
| # ========= 第三步:遍历四个模态目录,按股票 ID 归并文件路径 ========= | |
| def load_stock_modal_index(path: Path) -> Dict[str, Dict[str, Any]]: | |
| meta: Dict[str, Dict[str, Any]] = {} | |
| with path.open("r", encoding="utf-8") as f: | |
| for line in f: | |
| line = line.strip() | |
| if not line: | |
| continue | |
| obj = json.loads(line) | |
| meta[obj["stock_id"]] = obj | |
| return meta | |
| def add_files_by_stock( | |
| base_dir: Path, | |
| pattern: str, | |
| key: str, | |
| mapping: Dict[str, Dict[str, Any]], | |
| ): | |
| """ | |
| 遍历 base_dir 下所有匹配 pattern 的文件, | |
| 根据文件名里的股票代码归类到 mapping[stock_id][key] 列表。 | |
| 假设文件名类似 AAPL_XXXX.* 或 600000_XXXX.*,stock_id 是前缀。 | |
| 根据真实命名规则修改解析方式即可。 | |
| """ | |
| if not base_dir.is_dir(): | |
| return | |
| files = list(base_dir.rglob(pattern)) | |
| for path in tqdm(files, desc=f"Indexing {key} files"): | |
| stem = path.stem | |
| stock_id = stem.split("_")[0] # 按实际文件名规则调整 | |
| if stock_id not in mapping: | |
| continue | |
| mapping.setdefault(stock_id, {}).setdefault(key, []).append(str(path)) | |
| def build_four_modal_index(): | |
| stock_meta = load_stock_modal_index(OUT_STOCK_MODAL_INDEX) | |
| # 初始化四模态文件列表 | |
| for rec in stock_meta.values(): | |
| rec.setdefault("image_files", []) | |
| rec.setdefault("time_series_files", []) | |
| rec.setdefault("table_files", []) | |
| rec.setdefault("text_files", []) | |
| # 1) 图像 | |
| image_root = DATA_ROOT / "image" | |
| add_files_by_stock(image_root, "*.png", "image_files", stock_meta) | |
| # 2) 时间序列 | |
| ts_root = DATA_ROOT / "time_series" | |
| add_files_by_stock(ts_root, "*.csv", "time_series_files", stock_meta) | |
| add_files_by_stock(ts_root, "*.zip", "time_series_files", stock_meta) | |
| # 3) 表格 | |
| table_root = DATA_ROOT / "table" | |
| add_files_by_stock(table_root, "*.json", "table_files", stock_meta) | |
| add_files_by_stock(table_root, "*.jsonl", "table_files", stock_meta) | |
| add_files_by_stock(table_root, "*.zip", "table_files", stock_meta) | |
| # 4) 文本 | |
| text_root = DATA_ROOT / "text" | |
| add_files_by_stock(text_root, "*.jsonl", "text_files", stock_meta) | |
| add_files_by_stock(text_root, "*.zip", "text_files", stock_meta) | |
| OUT_FOUR_MODAL_INDEX.parent.mkdir(parents=True, exist_ok=True) | |
| with OUT_FOUR_MODAL_INDEX.open("w", encoding="utf-8") as f: | |
| for stock_id, rec in stock_meta.items(): | |
| f.write(json.dumps(rec, ensure_ascii=False) + "\n") | |
| print(f"[FinMultiTime] Four-modal file index saved to: {OUT_FOUR_MODAL_INDEX}") | |
| # ========= 主入口 ========= | |
| if __name__ == "__main__": | |
| # 1) 如果本地没有完整仓库就下载;已经完整就直接跳过 | |
| download_repo_if_needed() | |
| # 2) 构建股票层面的模态存在标记 | |
| build_stock_modal_index() | |
| # 3) 构建四模态文件路径索引 | |
| build_four_modal_index() | |