File size: 29,687 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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
#!/usr/bin/env python3
"""
K线图 + 新闻 指令微调数据生成脚本
生成 LLaVA 格式的训练数据,结合 K 线图和新闻摘要进行情感分析和趋势判断

输出两个版本:
- 原版 (finmultitime_kline_news_llavaplus.json): 完整新闻,用于大模型训练
- 短版 (finmultitime_kline_news_llavaplus_short.json): 限制长度,用于 7B 模型训练
"""

from __future__ import annotations
import json
import random
import os
from pathlib import Path
from typing import Dict, Any, List, Optional, Tuple
from datetime import datetime
from tqdm import tqdm
import re
import requests
import sys

# ========= NIM API 配置 =========
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"

# ========= 配置 =========
random.seed(42)

# 数据根目录
DATA_ROOT = Path("/workspace/data/finmultitime_hf")

# 输出文件
OUT_PATH_FULL = Path("/workspace/data/finmultitime_hf/finmultitime_kline_news_llavaplus.json")
OUT_PATH_SHORT = Path("/workspace/data/finmultitime_hf/finmultitime_kline_news_llavaplus_short.json")

# ========= 新闻采样配置 =========
# 原版配置 (完整新闻)
MAX_NEWS_PER_SAMPLE_FULL = 5     # 每个样本最多使用的新闻条数
MAX_NEWS_CHARS_FULL = None       # 每条新闻最大字符数(None 表示不截断)
MAX_PROMPT_CHARS_FULL = None     # prompt 最大字符数(None 表示不限制)

# 短版配置 (用于 7B 模型训练)
MAX_NEWS_PER_SAMPLE_SHORT = 3    # 每个样本最多使用的新闻条数
MAX_NEWS_CHARS_SHORT = 1500      # 每条新闻最大字符数
MAX_PROMPT_CHARS_SHORT = 8000    # prompt 最大字符数 (约 2600 tokens,留余量给回答)


def log(msg: str):
    print(msg, flush=True)


# ========= 文本清理 =========

def clean_mojibake(text: str) -> str:
    """清理编码乱码(Windows-1252 误读为 UTF-8 产生的乱码)
    
    常见乱码映射:
    - 禄 → » (right double angle quote)
    - 鈥? → — (em dash) 或 ' (smart quote)
    - 鈥淭 → "T (left double quote)
    - 鈥渕 → "m (left double quote)
    - 鈥檚 → 's (right single quote)
    
    注意:替换顺序很重要!长的模式必须在短的之前,否则短的会先匹配。
    """
    # 使用列表保证顺序:长的在前,短的在后
    replacements = [
        # 先处理长的组合模式
        ("鈥檚", "'s"),
        ("鈥檛", "'t"),
        ("鈥檝", "'v"),
        ("鈥檒", "'l"),
        ("鈥檙", "'r"),
        ("鈥榮", "'s"),
        ("鈥淭", '"T'),
        ("鈥渕", '"m'),
        ("鈥漑", '"['),
        ("鈥?", "—"),  # em dash with ?
        # 再处理短的单字符模式
        ("鈥", '"'),   # 单独的鈥
        ("禄", "»"),
        ("芦", "«"),
        # 其他常见乱码
        ("脙聝", "Ã"),
        ("脗", ""),
        ("锟斤拷", ""),
    ]
    
    for bad, good in replacements:
        text = text.replace(bad, good)
    
    return text


# ========= NIM API 调用 =========

def call_nim(prompt: str, lang: str = "zh") -> str:
    """调用 NIM API 生成回答
    
    Args:
        prompt: 用户提示词
        lang: 语言,"zh" 中文 或 "en" 英文
    """
    headers = {
        "Authorization": f"Bearer {NIM_API_KEY}",
        "Content-Type": "application/json",
    }
    
    if lang == "zh":
        system_content = (
            "你是一名专业金融分析师,已经看到了题目中提到的 K 线图和相关新闻。"
            "请用简洁、客观的中文回答用户问题,回答控制在 3–6 句,"
            "严格按照指定的小标题结构输出,不要编造具体数值或未提及的事件。"
        )
    else:
        system_content = (
            "You are a professional financial analyst who has seen the K-line chart and related news mentioned in the question. "
            "Please answer the user's question concisely and objectively in English. Keep the answer to 3-6 sentences, "
            "strictly follow the specified subheading structure, and do not fabricate specific numbers or unmentioned events."
        )
    
    payload = {
        "model": MODEL_NAME,
        "messages": [
            {"role": "system", "content": system_content},
            {"role": "user", "content": prompt},
        ],
        "temperature": 0.4,
        "max_tokens": 1024,
    }
    
    try:
        resp = requests.post(NIM_ENDPOINT, headers=headers, json=payload, timeout=120)
        resp.raise_for_status()
        data = resp.json()
        content = data["choices"][0]["message"]["content"].strip()
        return content
    except Exception as e:
        log(f"[NIM ERROR] {e}")
        # 返回默认回答
        if lang == "zh":
            return (
                "【新闻情感】综合新闻摘要,整体情感偏向中性。\n\n"
                "【走势关联】K线走势与新闻情感基本吻合。\n\n"
                "【综合判断】短期内可能维持震荡走势。"
            )
        else:
            return (
                "【News Sentiment】The overall sentiment appears neutral.\n\n"
                "【Price Correlation】The price movement aligns with the news sentiment.\n\n"
                "【Overall Judgment】The stock may continue range-bound trading in the short term."
            )


# ========= 路径查找函数 =========

def get_hs300_image_dir(stock_id: str) -> Optional[Path]:
    """获取 HS300 股票的图像目录"""
    img_dir = DATA_ROOT / "image" / "HS300_image" / "HS300_image" / stock_id
    return img_dir if img_dir.exists() else None


def get_sp500_image_dir(ticker: str) -> Optional[Path]:
    """获取 SP500 股票的图像目录(按首字母分目录)"""
    first_letter = ticker[0].lower()
    img_dir = DATA_ROOT / "image" / "image" / f"S&P500_image_{first_letter}" / ticker.lower()
    return img_dir if img_dir.exists() else None


def get_hs300_news_file(stock_id: str) -> Optional[Path]:
    """获取 HS300 股票的新闻文件(文件名包含公司名)"""
    news_dir = DATA_ROOT / "text" / "hs300news_summary" / "hs300news_summary"
    if not news_dir.exists():
        return None
    # 文件名格式: {股票代码}_{公司名}.jsonl
    for f in news_dir.iterdir():
        if f.name.startswith(stock_id + "_") and f.suffix == ".jsonl":
            return f
    return None


def get_sp500_news_file(ticker: str) -> Optional[Path]:
    """获取 SP500 股票的新闻文件(新闻文件名是大写)"""
    # 新闻文件名是大写
    news_file = DATA_ROOT / "text" / "sp500_news" / "sp500_news" / f"{ticker.upper()}.jsonl"
    return news_file if news_file.exists() else None


# ========= 新闻处理函数 =========

def load_news(
    news_file: Path, 
    max_count: int = MAX_NEWS_PER_SAMPLE_SHORT, 
    lang: str = "zh",
    time_range: Optional[Tuple[str, str]] = None,
    ticker: Optional[str] = None,
) -> List[Dict[str, Any]]:
    """加载并采样新闻
    
    Args:
        news_file: 新闻文件路径
        max_count: 最多返回的新闻条数
        lang: "zh" 使用 summary 字段 (HS300), "en" 使用 Article 字段 (SP500)
        time_range: 时间范围 (start_date, end_date),格式为 'YYYY-MM-DD',用于过滤新闻
        ticker: 股票代码(SP500),用于验证新闻是否与该股票相关
    
    Returns:
        过滤和采样后的新闻列表(按时间排序)
    """
    news_list = []
    # 根据语言选择内容字段
    content_field = "summary" if lang == "zh" else "Article"
    # 日期字段:HS300 用 datetime, SP500 用 Date
    date_field = "datetime" if lang == "zh" else "Date"
    
    try:
        with open(news_file, "r", encoding="utf-8") as f:
            for line in f:
                if not line.strip():
                    continue
                try:
                    item = json.loads(line)
                    # 只保留有内容的新闻
                    content = item.get(content_field, "")
                    if not content or str(content).lower() == "nan" or len(str(content)) < 10:
                        continue
                    
                    # 时间范围过滤
                    if time_range:
                        news_date = item.get(date_field, "")
                        if news_date:
                            # 提取日期部分 (YYYY-MM-DD)
                            news_date_str = str(news_date)[:10]
                            start_date, end_date = time_range
                            # 只保留在时间范围内的新闻
                            if not (start_date <= news_date_str <= end_date):
                                continue
                    
                    # SP500: 验证新闻是否与该股票相关
                    if ticker and lang == "en":
                        # 检查新闻内容或标题是否提及该股票
                        title = item.get("Article_title", "") or ""
                        # 如果新闻中完全没有提到该股票代码,跳过
                        ticker_upper = ticker.upper()
                        if ticker_upper not in str(content).upper() and ticker_upper not in str(title).upper():
                            continue
                    
                    # 统一使用 summary 字段存储内容
                    item["summary"] = str(content)
                    news_list.append(item)
                except json.JSONDecodeError:
                    continue
    except Exception as e:
        log(f"[WARN] Failed to load news from {news_file}: {e}")
        return []
    
    # 按日期排序(最新的在前)
    news_list.sort(key=lambda x: str(x.get(date_field, ""))[:10], reverse=True)
    
    # 随机采样(如果数量超过限制)
    if len(news_list) > max_count:
        # 优先保留最新的一半,随机采样另一半
        recent_count = max_count // 2
        recent_news = news_list[:recent_count]
        older_news = news_list[recent_count:]
        sampled_older = random.sample(older_news, min(len(older_news), max_count - recent_count))
        news_list = recent_news + sampled_older
        # 重新按时间排序
        news_list.sort(key=lambda x: str(x.get(date_field, ""))[:10], reverse=True)
    
    return news_list


def format_news_text(
    news_list: List[Dict[str, Any]], 
    lang: str = "zh",
    max_chars_per_news: Optional[int] = None,
) -> str:
    """将新闻列表格式化为文本
    
    Args:
        news_list: 新闻列表
        lang: 语言
        max_chars_per_news: 每条新闻最大字符数(None 表示不截断)
    """
    formatted = []
    for i, item in enumerate(news_list, 1):
        summary = str(item.get("summary", "")).strip()
        # 清理乱码
        summary = clean_mojibake(summary)
        
        # 截断过长新闻
        if max_chars_per_news and len(summary) > max_chars_per_news:
            summary = summary[:max_chars_per_news] + "..."
        
        # HS300 用 datetime, SP500 用 Date
        dt = item.get("datetime", "") or item.get("Date", "")
        # HS300 用 title, SP500 用 Article_title
        title = item.get("title", "") or item.get("Article_title", "")
        # 清理标题乱码
        if title:
            title = clean_mojibake(str(title))
        
        if title and str(title).lower() != "nan" and title.strip():
            formatted.append(f"[{i}] ({dt}) {title}: {summary}")
        else:
            formatted.append(f"[{i}] ({dt}) {summary}")
    
    return "\n".join(formatted)


def parse_image_period(image_name: str, lang: str = "zh") -> Optional[str]:
    """从图像文件名解析时间段
    
    Args:
        image_name: 图像文件名,如 '000001.SZ_2020_H1_candlestick.png'
        lang: 语言,"zh" 返回中文格式,"en" 返回英文格式
    
    Returns:
        中文: '2020年上半年'
        英文: '2020 H1'
    """
    match = re.search(r"(\d{4})_H([12])", image_name)
    if match:
        year, half = match.groups()
        if lang == "zh":
            half_text = "上半年" if half == "1" else "下半年"
            return f"{year}年{half_text}"
        else:
            return f"{year} H{half}"
    return None


def parse_image_time_range(image_name: str) -> Optional[Tuple[str, str]]:
    """从图像文件名解析时间范围
    
    Args:
        image_name: 图像文件名,如 '000001.SZ_2020_H1_candlestick.png'
    
    Returns:
        (start_date, end_date) 格式为 'YYYY-MM-DD'
        例如 2020_H1 -> ('2020-01-01', '2020-06-30')
    """
    match = re.search(r"(\d{4})_H([12])", image_name)
    if match:
        year, half = match.groups()
        if half == "1":
            return (f"{year}-01-01", f"{year}-06-30")
        else:
            return (f"{year}-07-01", f"{year}-12-31")
    return None


# ========= 指令模板 =========

def build_kline_news_sample_zh(
    stock_id: str,
    image_path: str,
    news_text: str,
    period: str,
    difficulty: str = "medium",
    max_prompt_chars: Optional[int] = None,
) -> Optional[Dict[str, Any]]:
    """构建中文 K线+新闻 样本
    
    Args:
        max_prompt_chars: prompt 最大字符数,超过则返回 None
    
    Returns:
        样本字典,如果 prompt 太长则返回 None
    """
    
    user_text = (
        "<image>\n"
        f"你已经获得股票 {stock_id} 在{period}的日 K 线图。"
        f"同时,以下是该时间段内与该股票相关的新闻摘要:\n\n"
        f"{news_text}\n\n"
        "请严格按照下面三段结构,用简洁的中文做出分析:\n"
        "【新闻情感】判断这些新闻整体偏利好、利空还是中性,并说明主要依据(如业绩增长、政策利好、负面事件等)。\n"
        "【走势关联】结合 K 线图的走势特征,分析新闻情感与股价走势是否一致(如利好新闻是否伴随上涨),并指出可能的原因。\n"
        "【综合判断】综合新闻面和技术面,判断该股票短期内更可能延续当前趋势、出现反转还是震荡,并给出 1 句话理由。\n"
        "注意:不要预测具体价格,不要编造新闻中未提及的事件,只基于提供的信息做定性分析。"
    )
    
    # 检查 prompt 长度
    if max_prompt_chars and len(user_text) > max_prompt_chars:
        return None
    
    # 使用 NIM API 生成回答
    nim_prompt = (
        f"你已经看到了股票 {stock_id} 在{period}的日 K 线图,以及以下新闻摘要:\n\n"
        f"{news_text[:2000]}...\n\n"  # 截断过长的新闻给 API
        "请用中文严格按照下面三段输出,每段 1-2 句,总字数控制在 3-6 句:\n"
        "【新闻情感】判断新闻整体偏利好、利空还是中性,并说明依据。\n"
        "【走势关联】分析新闻情感与K线走势是否一致,指出可能原因。\n"
        "【综合判断】判断短期走势方向(延续、反转或震荡),并给出理由。\n"
        "不要预测具体价格,不要编造未提及的事件。"
    )
    assistant = call_nim(nim_prompt, lang="zh")
    
    return {
        "id": None,
        "image": Path(image_path).name,
        "conversations": [
            {"from": "human", "value": user_text},
            {"from": "gpt", "value": assistant},
        ],
        "task_type": "kline_news_sentiment",
        "difficulty": difficulty,
        "images": [image_path],
        "news_count": len(news_text.split("\n")),
        "prompt_chars": len(user_text),
    }


def build_kline_news_sample_en(
    ticker: str,
    image_path: str,
    news_text: str,
    period: str,
    difficulty: str = "medium",
    max_prompt_chars: Optional[int] = None,
) -> Optional[Dict[str, Any]]:
    """构建英文 K线+新闻 样本
    
    Args:
        max_prompt_chars: prompt 最大字符数,超过则返回 None
    
    Returns:
        样本字典,如果 prompt 太长则返回 None
    """
    
    user_text = (
        "<image>\n"
        f"You have been given the daily K-line chart of stock {ticker} for {period}. "
        f"Below are news summaries related to this stock during the same period:\n\n"
        f"{news_text}\n\n"
        "Please analyze according to the following three-part structure:\n"
        "【News Sentiment】Determine whether the overall sentiment of these news is bullish, bearish, or neutral, "
        "and explain the main basis (e.g., earnings growth, policy support, negative events).\n"
        "【Price Correlation】Based on the K-line chart pattern, analyze whether the news sentiment aligns with "
        "the stock price movement, and explain possible reasons.\n"
        "【Overall Judgment】Combining fundamental news and technical analysis, determine whether the stock is "
        "more likely to continue its current trend, reverse, or consolidate in the short term, with a brief explanation.\n"
        "Note: Do not predict specific prices or fabricate events not mentioned in the news."
    )
    
    # 检查 prompt 长度
    if max_prompt_chars and len(user_text) > max_prompt_chars:
        return None
    
    # 使用 NIM API 生成回答
    nim_prompt = (
        f"You have seen the daily K-line chart of stock {ticker} for {period}, along with these news summaries:\n\n"
        f"{news_text[:2000]}...\n\n"  # 截断过长的新闻给 API
        "Please output in English strictly following the three sections below, 1-2 sentences each, total 3-6 sentences:\n"
        "【News Sentiment】Determine if the news is bullish, bearish, or neutral, with reasoning.\n"
        "【Price Correlation】Analyze if news sentiment aligns with K-line movement, explain why.\n"
        "【Overall Judgment】Predict short-term direction (continue, reverse, or consolidate) with reason.\n"
        "Do not predict specific prices or fabricate unmentioned events."
    )
    assistant = call_nim(nim_prompt, lang="en")
    
    return {
        "id": None,
        "image": Path(image_path).name,
        "conversations": [
            {"from": "human", "value": user_text},
            {"from": "gpt", "value": assistant},
        ],
        "task_type": "kline_news_sentiment",
        "difficulty": difficulty,
        "images": [image_path],
        "news_count": len(news_text.split("\n")),
        "prompt_chars": len(user_text),
    }


# ========= 主流程 =========

def process_hs300(
    max_samples: Optional[int] = None,
    max_news: int = MAX_NEWS_PER_SAMPLE_SHORT,
    max_news_chars: Optional[int] = None,
    max_prompt_chars: Optional[int] = None,
) -> List[Dict[str, Any]]:
    """处理 HS300 数据
    
    Args:
        max_samples: 最大样本数,None 表示不限制
        max_news: 每个样本最多新闻条数
        max_news_chars: 每条新闻最大字符数
        max_prompt_chars: prompt 最大字符数
    """
    samples = []
    skipped_long = 0
    
    # 遍历所有 HS300 股票
    hs300_img_root = DATA_ROOT / "image" / "HS300_image" / "HS300_image"
    if not hs300_img_root.exists():
        log(f"[WARN] HS300 image dir not found: {hs300_img_root}")
        return samples
    
    stock_dirs = [d for d in hs300_img_root.iterdir() if d.is_dir()]
    log(f"[HS300] Found {len(stock_dirs)} stock directories")
    
    for stock_dir in tqdm(stock_dirs, desc="Processing HS300"):
        # 检查是否达到限制
        if max_samples and len(samples) >= max_samples:
            break
            
        stock_id = stock_dir.name
        
        # 获取新闻文件
        news_file = get_hs300_news_file(stock_id)
        if not news_file:
            continue
        
        # 获取所有图像
        images = list(stock_dir.glob("*.png"))
        if not images:
            continue
        
        # 随机选一张图像生成样本(限制时)
        selected_images = [random.choice(images)] if max_samples else images
        
        for img_path in selected_images:
            if max_samples and len(samples) >= max_samples:
                break
            
            # 解析图片的时间范围
            time_range = parse_image_time_range(img_path.name)
            period = parse_image_period(img_path.name, lang="zh")
            if not period:
                period = "某一时间段"
            
            # 加载该时间段内的新闻
            news_list = load_news(news_file, max_count=max_news, lang="zh", time_range=time_range)
            if not news_list:
                # 如果该时间段没有新闻,跳过这张图片
                continue
            
            news_text = format_news_text(news_list, lang="zh", max_chars_per_news=max_news_chars)
            
            try:
                sample = build_kline_news_sample_zh(
                    stock_id=stock_id,
                    image_path=str(img_path),
                    news_text=news_text,
                    period=period,
                    difficulty="medium",
                    max_prompt_chars=max_prompt_chars,
                )
                if sample is None:
                    skipped_long += 1
                    continue
                sample["id"] = f"HS300_{stock_id}_kline_news_{len(samples)}"
                samples.append(sample)
                log(f"[HS300] {len(samples)}/{max_samples or '∞'} - {stock_id} ({period})")
            except Exception as e:
                log(f"[WARN] Failed on {stock_id}: {e}")
                continue
    
    if skipped_long > 0:
        log(f"[HS300] Skipped {skipped_long} samples due to prompt length")
    
    return samples


def process_sp500(
    max_samples: Optional[int] = None,
    max_news: int = MAX_NEWS_PER_SAMPLE_SHORT,
    max_news_chars: Optional[int] = None,
    max_prompt_chars: Optional[int] = None,
) -> List[Dict[str, Any]]:
    """处理 SP500 数据
    
    Args:
        max_samples: 最大样本数,None 表示不限制
        max_news: 每个样本最多新闻条数
        max_news_chars: 每条新闻最大字符数
        max_prompt_chars: prompt 最大字符数
    """
    samples = []
    skipped_long = 0
    
    # 遍历所有 SP500 图像目录 (a-z)
    sp500_img_root = DATA_ROOT / "image" / "image"
    if not sp500_img_root.exists():
        log(f"[WARN] SP500 image dir not found: {sp500_img_root}")
        return samples
    
    # 收集所有股票目录
    stock_dirs = []
    for letter_dir in sp500_img_root.iterdir():
        if letter_dir.is_dir() and letter_dir.name.startswith("S&P500_image_"):
            for stock_dir in letter_dir.iterdir():
                if stock_dir.is_dir():
                    stock_dirs.append(stock_dir)
    
    log(f"[SP500] Found {len(stock_dirs)} stock directories")
    
    for stock_dir in tqdm(stock_dirs, desc="Processing SP500"):
        # 检查是否达到限制
        if max_samples and len(samples) >= max_samples:
            break
            
        ticker = stock_dir.name.upper()
        
        # 获取新闻文件
        news_file = get_sp500_news_file(ticker)
        if not news_file:
            continue
        
        # 获取所有图像
        images = list(stock_dir.glob("*.png"))
        if not images:
            continue
        
        # 随机选图像生成样本
        if max_samples:
            selected_images = [random.choice(images)]
        else:
            selected_images = random.sample(images, min(len(images), 3))
        
        for img_path in selected_images:
            if max_samples and len(samples) >= max_samples:
                break
            
            # 解析图片的时间范围
            time_range = parse_image_time_range(img_path.name)
            period = parse_image_period(img_path.name, lang="en")
            if not period:
                period = "a certain period"
            
            # 加载该时间段内且与该股票相关的新闻
            news_list = load_news(news_file, max_count=max_news, lang="en", time_range=time_range, ticker=ticker)
            if not news_list:
                # 如果该时间段没有相关新闻,跳过这张图片
                continue
            
            news_text = format_news_text(news_list, lang="en", max_chars_per_news=max_news_chars)
            
            try:
                sample = build_kline_news_sample_en(
                    ticker=ticker,
                    image_path=str(img_path),
                    news_text=news_text,
                    period=period,
                    difficulty="medium",
                    max_prompt_chars=max_prompt_chars,
                )
                if sample is None:
                    skipped_long += 1
                    continue
                sample["id"] = f"SP500_{ticker}_kline_news_{len(samples)}"
                samples.append(sample)
                log(f"[SP500] {len(samples)}/{max_samples or '∞'} - {ticker} ({period})")
            except Exception as e:
                log(f"[WARN] Failed on {ticker}: {e}")
                continue
    
    if skipped_long > 0:
        log(f"[SP500] Skipped {skipped_long} samples due to prompt length")
    
    return samples


def save_samples(samples: List[Dict[str, Any]], out_path: Path, version_name: str):
    """保存样本并打印统计"""
    with out_path.open("w", encoding="utf-8") as f:
        json.dump(samples, f, ensure_ascii=False, indent=2)
    
    # 统计
    hs300_count = sum(1 for s in samples if s["id"].startswith("HS300"))
    sp500_count = sum(1 for s in samples if s["id"].startswith("SP500"))
    prompt_lengths = [s.get("prompt_chars", 0) for s in samples]
    
    log(f"\n[{version_name}] Statistics:")
    log(f"  - Total: {len(samples)}")
    log(f"  - HS300: {hs300_count}")
    log(f"  - SP500: {sp500_count}")
    if prompt_lengths:
        log(f"  - Prompt chars: min={min(prompt_lengths)}, max={max(prompt_lengths)}, avg={sum(prompt_lengths)//len(prompt_lengths)}")
    log(f"  - Output: {out_path}")


def main(max_samples: Optional[int] = None, generate_full: bool = False, generate_short: bool = True):
    """
    Args:
        max_samples: 最大样本数(每个市场各生成 max_samples/2 个),None 表示不限制
        generate_full: 是否生成完整版(用于大模型训练)
        generate_short: 是否生成短版本(用于 7B 模型训练)
    """
    log("=" * 60)
    log("K线图 + 新闻 指令微调数据生成 (NIM API)")
    log("=" * 60)
    if max_samples:
        log(f"[CONFIG] max_samples = {max_samples} (HS300: {max_samples//2}, SP500: {max_samples//2})")
    log(f"[CONFIG] generate_full = {generate_full}")
    log(f"[CONFIG] generate_short = {generate_short}")
    
    OUT_PATH_FULL.parent.mkdir(parents=True, exist_ok=True)
    
    hs300_limit = max_samples // 2 if max_samples else None
    sp500_limit = max_samples // 2 if max_samples else None
    
    # ========== 生成完整版 ==========
    if generate_full:
        log("\n" + "=" * 60)
        log("[FULL VERSION] Generating full-length samples...")
        log("=" * 60)
        
        all_samples_full = []
        
        log("\n[1/2] Processing HS300 (FULL)...")
        hs300_full = process_hs300(
            max_samples=hs300_limit,
            max_news=MAX_NEWS_PER_SAMPLE_FULL,
            max_news_chars=MAX_NEWS_CHARS_FULL,
            max_prompt_chars=MAX_PROMPT_CHARS_FULL,
        )
        all_samples_full.extend(hs300_full)
        
        log("\n[2/2] Processing SP500 (FULL)...")
        sp500_full = process_sp500(
            max_samples=sp500_limit,
            max_news=MAX_NEWS_PER_SAMPLE_FULL,
            max_news_chars=MAX_NEWS_CHARS_FULL,
            max_prompt_chars=MAX_PROMPT_CHARS_FULL,
        )
        all_samples_full.extend(sp500_full)
        
        random.shuffle(all_samples_full)
        save_samples(all_samples_full, OUT_PATH_FULL, "FULL")
    
    # ========== 生成短版 ==========
    if generate_short:
        log("\n" + "=" * 60)
        log("[SHORT VERSION] Generating short samples for 7B model...")
        log("=" * 60)
        
        # 重置随机种子确保一致性
        random.seed(42)
        
        all_samples_short = []
        
        log("\n[1/2] Processing HS300 (SHORT)...")
        hs300_short = process_hs300(
            max_samples=hs300_limit,
            max_news=MAX_NEWS_PER_SAMPLE_SHORT,
            max_news_chars=MAX_NEWS_CHARS_SHORT,
            max_prompt_chars=MAX_PROMPT_CHARS_SHORT,
        )
        all_samples_short.extend(hs300_short)
        
        log("\n[2/2] Processing SP500 (SHORT)...")
        sp500_short = process_sp500(
            max_samples=sp500_limit,
            max_news=MAX_NEWS_PER_SAMPLE_SHORT,
            max_news_chars=MAX_NEWS_CHARS_SHORT,
            max_prompt_chars=MAX_PROMPT_CHARS_SHORT,
        )
        all_samples_short.extend(sp500_short)
        
        random.shuffle(all_samples_short)
        save_samples(all_samples_short, OUT_PATH_SHORT, "SHORT")
    
    log("\n" + "=" * 60)
    log("[DONE] All data generation complete!")
    log("=" * 60)


if __name__ == "__main__":
    # ============ 测试时设置 max_samples,正式运行设为 None ============
    # main(max_samples=10)  # 测试:每个市场各 5 条
    # main(max_samples=None, generate_full=True, generate_short=True)  # 生成两个版本
    main(max_samples=None, generate_full=False, generate_short=True)  # 只生成 SHORT 版本