File size: 7,497 Bytes
2e208c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
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()