Download fin-mm/code/yahoo_instruction_data.py from GoldenGrapeGentleman1/FinMM-code: direct link, hf CLI and curl.
- Browser
- Download file 6.83 kB
-
https://huggingface.co/GoldenGrapeGentleman1/FinMM-code/resolve/main/fin-mm/code/yahoo_instruction_data.py
- Command line
-
hf download hf://GoldenGrapeGentleman1/FinMM-code/fin-mm/code/yahoo_instruction_data.py
-
curl -L -o yahoo_instruction_data.py https://huggingface.co/GoldenGrapeGentleman1/FinMM-code/resolve/main/fin-mm/code/yahoo_instruction_data.py
6.83 kB
| # NVIDIA NIM 配置 (建议使用 Llama 3.2 Vision 系列) | |
| NIM_API_KEY = "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" # <--- 替换为你的 Key | |
| NIM_ENDPOINT = "https://integrate.api.nvidia.com/v1/chat/completions" | |
| MODEL_NAME = "meta/llama-3.2-90b-vision-instruct" | |
| import os | |
| import json | |
| import random | |
| import base64 | |
| from pathlib import Path | |
| from tqdm import tqdm | |
| import requests | |
| # ================= 配置 ================= | |
| HIST_DIR = Path("/workspace/data/charts/hist") | |
| FULL_DIR = Path("/workspace/data/charts/full") | |
| OUT_PATH = Path("/workspace/data/llava_fin_tool_instruct.json") | |
| # 工具名,和你之后在 LLaVA-Plus 里注册的一致即可 | |
| BAGEL_TOOL = "bagel_financial_gen" | |
| TIMESNET_TOOL = "timesnet_forecast" | |
| PLOT_TOOL = "plot_forecast" | |
| def encode_image(image_path: str) -> str: | |
| with open(image_path, "rb") as f: | |
| return base64.b64encode(f.read()).decode("utf-8") | |
| def call_vlm_analyze(image_path: str, ticker: str): | |
| """ | |
| 让 VLM 看一张历史 K 线图,输出: | |
| 1)简短图表分析; | |
| 2)一个合理的“用户问题”自然语言。 | |
| """ | |
| img_b64 = encode_image(image_path) | |
| prompt = f""" | |
| 你是一名擅长技术分析的量化交易员,正在观察股票 {ticker} 的历史 K 线图。 | |
| 任务1:用 2~3 句话,用中文简要分析这张图的走势特征(例如:上涨/下跌、震荡、波动率、是否接近支撑/阻力等)。 | |
| 任务2:基于这张图的走势,用中文写出 1 条自然的“用户问题”,向一个多模态 AI 助手询问未来走势。例如: | |
| - 你觉得接下来10天大概率会怎么走? | |
| - 请给出未来一段时间的可能走势场景,并提醒风险。 | |
| 只输出下面这个 JSON 对象,不要输出其他内容: | |
| {{ | |
| "analysis": "...你对图的分析...", | |
| "user_question": "...用户会问的问题..." | |
| }} | |
| """ | |
| headers = { | |
| "Authorization": f"Bearer {NIM_API_KEY}", | |
| "Content-Type": "application/json", | |
| } | |
| payload = { | |
| "model": MODEL_NAME, | |
| "messages": [ | |
| { | |
| "role": "user", | |
| "content": [ | |
| {"type": "text", "text": prompt}, | |
| { | |
| "type": "image_url", | |
| "image_url": {"url": f"data:image/png;base64,{img_b64}"}, | |
| }, | |
| ], | |
| } | |
| ], | |
| "temperature": 0.6, | |
| "max_tokens": 512, | |
| } | |
| resp = requests.post(NIM_ENDPOINT, headers=headers, json=payload, timeout=120) | |
| if resp.status_code != 200: | |
| print("VLM 调用失败:", resp.status_code, resp.text[:200]) | |
| return None | |
| text = resp.json()["choices"][0]["message"]["content"] | |
| # 清理可能的 markdown 代码块 | |
| text = text.replace("``````", "").strip() | |
| try: | |
| data = json.loads(text) | |
| return data # {"analysis": "...", "user_question": "..."} | |
| except Exception as e: | |
| print("JSON 解析失败,返回原文用于调试:", text[:200]) | |
| return None | |
| def build_conversation(pair_id: int, hist_path: str, full_path: str, ticker: str, vlm_out: dict): | |
| """ | |
| 根据 VLM 的分析结果,构造一条 LLaVA-Plus 风格数据: | |
| conversations: [human, gpt],其中 gpt 的内容是一个 JSON(thoughts/actions/value)。 | |
| """ | |
| analysis = vlm_out["analysis"] | |
| user_q = vlm_out["user_question"] | |
| # 随机决定使用哪种工具策略 | |
| mode = random.choice(["bagel_only", "timesnet_then_plot"]) | |
| if mode == "bagel_only": | |
| thoughts = ( | |
| f"用户想基于当前的历史走势预测未来价格路径。" | |
| f"从图上看:{analysis}。" | |
| f"直接调用 {BAGEL_TOOL} 生成一张包含未来走势的预测图像最合适。" | |
| ) | |
| actions = [ | |
| { | |
| "API_name": BAGEL_TOOL, | |
| "API_params": { | |
| "hist_image_path": hist_path, | |
| "scenario": "中性趋势场景:延续当前走势并考虑适度波动", | |
| }, | |
| } | |
| ] | |
| value = ( | |
| "好的,我会先用图像生成工具基于当前走势给出一幅可能的未来行情图," | |
| "请注意这只是多种可能场景之一,不构成投资建议。" | |
| ) | |
| else: | |
| thoughts = ( | |
| f"用户不仅想看图像,还希望了解具体的数值预测。" | |
| f"从图上看:{analysis}。" | |
| f"可以先调用 {TIMESNET_TOOL} 得到未来价格序列,再调用 {PLOT_TOOL} 画出预测图。" | |
| ) | |
| actions = [ | |
| { | |
| "API_name": TIMESNET_TOOL, | |
| "API_params": {"ticker": ticker, "hist_data_points": 60, "pred_horizon": 10}, | |
| }, | |
| { | |
| "API_name": PLOT_TOOL, | |
| "API_params": {"hist_image_path": hist_path, "forecast_data": "<PREDICTED_SERIES>"}, | |
| }, | |
| ] | |
| value = ( | |
| "我会先根据历史数据做一个未来10个周期的数值预测,然后把预测结果和当前K线一起画成图," | |
| "这样你既能看到大致走势,也能看到估计的价格区间。请注意预测存在误差和风险。" | |
| ) | |
| gpt_json = { | |
| "thoughts": thoughts, | |
| "actions": actions, | |
| "value": value, | |
| } | |
| conv = { | |
| "id": f"fin_tool_{pair_id}", | |
| "image": hist_path, | |
| "conversations": [ | |
| {"from": "human", "value": f"<image>\n{user_q}"}, | |
| {"from": "gpt", "value": json.dumps(gpt_json, ensure_ascii=False, indent=2)}, | |
| ], | |
| } | |
| return conv | |
| def main(): | |
| # 1. 找到配对图片 | |
| pairs = [] | |
| hist_files = sorted(list(HIST_DIR.glob("*.png"))) | |
| for hist in hist_files: | |
| full = FULL_DIR / hist.name | |
| if full.exists(): | |
| ticker = hist.name.split("_")[0] | |
| pairs.append((str(hist), str(full), ticker)) | |
| print(f"找到 {len(pairs)} 对图片。") | |
| OUT_PATH.parent.mkdir(parents=True, exist_ok=True) | |
| conversations = [] | |
| # 为了先试跑,这里限制前 N 条;正式跑可以去掉 [:N] | |
| for i, (hist_path, full_path, ticker) in enumerate(tqdm(pairs, desc="生成多模态指令")): | |
| vlm_out = call_vlm_analyze(hist_path, ticker) | |
| if not vlm_out: | |
| continue | |
| conv = build_conversation(i, hist_path, full_path, ticker, vlm_out) | |
| conversations.append(conv) | |
| with open(OUT_PATH, "w", encoding="utf-8") as f: | |
| json.dump(conversations, f, ensure_ascii=False, indent=2) | |
| print(f"完成!生成 {len(conversations)} 条指令数据 -> {OUT_PATH}") | |
| if __name__ == "__main__": | |
| if NIM_API_KEY.startswith("nvapi-xxx"): | |
| print("请先在脚本中填写 NIM_API_KEY。") | |
| else: | |
| main() |