File size: 9,158 Bytes
e1715de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
from __future__ import annotations
import json
import random
from pathlib import Path
from typing import Dict, Any, List, Optional
import requests
import sys
from tqdm import tqdm

# ========= 配置 =========
NIM_API_KEY = "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"  # 换成你的
NIM_ENDPOINT = "https://integrate.api.nvidia.com/v1/chat/completions"
MODEL_NAME = "meta/llama-3.2-90b-vision-instruct"

# 上一步生成的 k 线索引
INPUT_INDEX = Path("/workspace/data/finmultitime_hf/finmultitime_kline_index.jsonl")
# 输出:直接供 LLaVA-Plus --data_path 使用
OUT_PATH   = Path("/workspace/data/finmultitime_hf/finmultitime_kline_llavaplus.json")

random.seed(42)


def log(msg: str):
    print(msg)
    sys.stdout.flush()


def call_nim(prompt: str) -> str:
    headers = {
        "Authorization": f"Bearer {NIM_API_KEY}",
        "Content-Type": "application/json",
    }
    payload = {
        "model": MODEL_NAME,
        "messages": [
            {
                "role": "system",
                "content": (
                    "你是一名专业量化分析师,已经看到了题目中提到的 K 线图或价格序列。"
                    "请用简洁、客观的中文回答用户问题,回答控制在 2–5 句,"
                    "严格按照指定的小标题结构输出,不要编造具体数值或未提及的事件。"
                ),
            },
            {"role": "user", "content": prompt},
        ],
        "temperature": 0.4,
        "max_tokens": 512,
    }
    log("[NIM] sending request...")
    resp = requests.post(NIM_ENDPOINT, headers=headers, json=payload, timeout=60)
    log(f"[NIM] status: {resp.status_code}")
    resp.raise_for_status()
    data = resp.json()
    content = data["choices"][0]["message"]["content"].strip()
    log(f"[NIM] got {len(content)} chars")
    return content


def file_exists_any(paths: List[str]) -> List[str]:
    return [p for p in paths if Path(p).is_file()]


# ==== 模板 1:单图 K 线阅读 ====

def build_kline_only_sample(
    base_rec: Dict[str, Any],
    image_path: str,
    difficulty: str = "easy",
) -> Dict[str, Any]:
    stock_id = base_rec["stock_id"]
    user_text = (
        "<image>\n"
        f"你已经看到了股票 {stock_id} 在一个固定时间窗口内的日 K 线图(包含价格和成交量)。"
        "请严格按照下面的三段结构,用简洁的中文回答问题:\n"
        "【总体趋势】判断该时间段内股价整体是上涨、下跌还是震荡,并用 1 句话概括上涨或下跌的大致节奏,例如“先跌后涨”“缓慢震荡上行”等。\n"
        "【关键波动】指出这段时间内最明显的 1–3 次急涨或急跌,大致说明发生在前段、中段还是末段,以及这些波动是顺势放大还是趋势中的回调。\n"
        "【交易含义】站在短线交易者角度,总结这段走势更偏向于高位追涨风险大、逢低布局机会多,还是应以观望为主,并给出 1 句简要理由(例如“频繁剧烈波动,追涨容易被套”)。\n"
        "注意:不要给出具体价格或收益百分比,不要编造任何图上看不到的消息或事件,只基于 K 线本身做定性判断。"
    )

    assistant = call_nim(
        "你已经仔细观察了一张股票日 K 线图(包含价格和成交量)。"
        "请用中文严格按照下面三段输出,每段 1 句左右,总字数控制在 3–5 句:\n"
        "【总体趋势】...\n"
        "【关键波动】...\n"
        "【交易含义】...\n"
        "不要写出具体价格数值或收益百分比,不要提及任何图上看不到的新闻或事件,只描述从 K 线本身能看到的走势特征和含义。"
    )

    sample = {
        "id": None,
        "image": Path(image_path).name,  # LLaVA-Plus 用相对文件名
        "conversations": [
            {"from": "human", "value": user_text},
            {"from": "gpt",   "value": assistant},
        ],
        "task_type": "kline_reading",
        "difficulty": difficulty,
        "images": [image_path],
        "timeseries_files": [],
        "table_files": [],
        "text_files": [],
    }
    return sample


# ==== 模板 2:图 + 时间序列趋势 ====

def build_kline_trend_sample(
    base_rec: Dict[str, Any],
    image_path: str,
    ts_path: str,
    difficulty: str = "easy",
    future_label: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
    stock_id = base_rec["stock_id"]
    user_text = (
        "<image>\n"
        f"你已经获得股票 {stock_id} 在一个固定时间窗口内的日 K 线图,以及同一时间段的收盘价时间序列。"
        "请严格按照下面三段结构,用简洁的中文做出分析:\n"
        "【历史趋势】综合 K 线和价格序列,判断该时间段内股价是缓慢上涨、震荡上行、区间震荡、震荡下跌还是快速下跌,并用 1 句话概括整体节奏(例如“前期横盘、后期快速拉升”)。\n"
        "【风险与机会】指出这段走势中最大的 1–2 个风险点(如高位放量长上影、大幅跳空下跌等)和 1–2 个潜在机会(如低位放量企稳、缩量回调等),并说明它们大致出现在前段、中段还是末段。\n"
        "【未来偏向】在不考虑估值和基本面信息的前提下,仅基于当前这段走势形态,判断接下来短期更可能是延续当前方向、出现方向性反转,还是维持区间震荡,并用 1 句话给出理由(如“放量突破箱体后回踩不深,更可能延续上涨”)。\n"
        "注意:不要预测具体价格或收益百分比,不要编造任何新闻或基本面事件,只基于走势形态和价格变化做方向性判断。"
    )

    assistant = call_nim(
        "你已经看到了某只股票一段时间内的日 K 线图和对应收盘价时间序列。"
        "请用中文严格按照下面三段输出,总 3–5 句:\n"
        "【历史趋势】...\n"
        "【风险与机会】...\n"
        "【未来偏向】...\n"
        "每段 1–2 句,不要写具体价格或收益数值,不要提及任何图上看不到的新闻或政策,只描述走势形态、风险和方向性判断。"
    )

    sample = {
        "id": None,
        "image": Path(image_path).name,
        "conversations": [
            {"from": "human", "value": user_text},
            {"from": "gpt",   "value": assistant},
        ],
        "task_type": "kline_trend",
        "difficulty": difficulty,
        "images": [image_path],
        "timeseries_files": [ts_path],
        "table_files": [],
        "text_files": [],
    }
    if future_label is not None:
        # 预留给你后续从 ts 里计算真实 10 日收益/方向
        sample["label"] = future_label
    return sample


def main(max_samples: Optional[int] = None):
    OUT_PATH.parent.mkdir(parents=True, exist_ok=True)

    records: List[Dict[str, Any]] = []
    with INPUT_INDEX.open("r", encoding="utf-8") as fin:
        for line in fin:
            if not line.strip():
                continue
            records.append(json.loads(line))

    log(f"[MAIN] kline records: {len(records)}")
    all_samples: List[Dict[str, Any]] = []
    count = 0

    for rec in tqdm(records, desc="Generating kline samples"):
        images = file_exists_any(rec.get("image_files", []))
        ts_files = file_exists_any(rec.get("time_series_files", []))
        if not images:
            continue

        templates: List[str] = []
        if images and ts_files:
            templates.extend(["kline_trend"] * 3)  # 让 trend 占比高一点
        templates.append("kline_reading")

        tpl = random.choice(templates)
        log(f"[MAIN] {rec['market']} {rec['stock_id']} tpl={tpl}")

        try:
            if tpl == "kline_trend" and ts_files:
                future_label = {
                    "future_return_10d": None,
                    "future_direction_10d": None,
                }
                sample = build_kline_trend_sample(
                    rec,
                    random.choice(images),
                    random.choice(ts_files),
                    difficulty="easy",
                    future_label=future_label,
                )
            else:
                sample = build_kline_only_sample(
                    rec,
                    random.choice(images),
                    difficulty="easy",
                )
        except Exception as e:
            log(f"[WARN] fail on {rec['stock_id']} ({tpl}): {e}")
            continue

        sample["id"] = f"{rec['market']}_{rec['stock_id']}_{tpl}_{count}"
        all_samples.append(sample)
        count += 1
        if max_samples is not None and count >= max_samples:
            break

    with OUT_PATH.open("w", encoding="utf-8") as f:
        json.dump(all_samples, f, ensure_ascii=False, indent=2)

    log(f"[OK] generated {count} samples -> {OUT_PATH}")


if __name__ == "__main__":
    # 先用小一点的 max_samples 验证一下,再放开
    main(max_samples=None)