#!/usr/bin/env python3
"""
用 pyecharts 生成专业期货图表
"""

import akshare as ak
from pyecharts.charts import Kline, Line, Bar, Grid, Page
from pyecharts import options as opts
from pyecharts.globals import ThemeType
import pandas as pd
import os

# 创建输出目录
output_dir = '/root/.openclaw/workspace/ppt_charts_pyecharts'
os.makedirs(output_dir, exist_ok=True)

# 获取历史日线数据 - 玉米期货主力合约
# 玉米期货在大连商品交易所(DCE)
hist = ak.futures_zh_daily_sina(symbol="C0")
hist = hist.tail(60).reset_index(drop=True)

# 准备K线数据 [open, close, low, high]
kline_data = []
for _, row in hist.iterrows():
    kline_data.append([
        float(row['open']),
        float(row['close']),
        float(row['low']),
        float(row['high'])
    ])

dates = hist['date'].tolist()

# 1. K线图 + MA均线
kline = (
    Kline(init_opts=opts.InitOpts(
        width="1200px",
        height="600px",
        theme=ThemeType.DARK,
        bg_color="#1a1a2e"
    ))
    .add_xaxis(dates)
    .add_yaxis(
        "K线",
        kline_data,
        itemstyle_opts=opts.ItemStyleOpts(
            color="#ef4444",  # 涨 红色
            color0="#22c55e",  # 跌 绿色
            border_color="#ef4444",
            border_color0="#22c55e"
        )
    )
    .set_global_opts(
        title_opts=opts.TitleOpts(
            title="玉米期货主力合约(C0) 走势",
            subtitle="数据来源: AKShare",
            title_textstyle_opts=opts.TextStyleOpts(color="#fff", font_size=20),
            subtitle_textstyle_opts=opts.TextStyleOpts(color="#aaa", font_size=12),
            pos_left="center"
        ),
        tooltip_opts=opts.TooltipOpts(
            trigger="axis",
            axis_pointer_type="cross",
            background_color="rgba(50,50,50,0.8)",
            border_color="#666",
            textstyle_opts=opts.TextStyleOpts(color="#fff")
        ),
        legend_opts=opts.LegendOpts(
            pos_top="10%",
            textstyle_opts=opts.TextStyleOpts(color="#fff")
        ),
        xaxis_opts=opts.AxisOpts(
            type_="category",
            axisline_opts=opts.AxisLineOpts(linestyle_opts=opts.LineStyleOpts(color="#666")),
            axislabel_opts=opts.LabelOpts(color="#aaa", rotate=45),
            splitline_opts=opts.SplitLineOpts(is_show=False)
        ),
        yaxis_opts=opts.AxisOpts(
            type_="value",
            axisline_opts=opts.AxisLineOpts(linestyle_opts=opts.LineStyleOpts(color="#666")),
            axislabel_opts=opts.LabelOpts(color="#aaa"),
            splitline_opts=opts.SplitLineOpts(
                linestyle_opts=opts.LineStyleOpts(color="#333", type_="dashed")
            )
        ),
        datazoom_opts=[
            opts.DataZoomOpts(type_="inside", range_start=0, range_end=100),
            opts.DataZoomOpts(type_="slider", range_start=0, range_end=100, pos_bottom="5%")
        ]
    )
)

# 计算并添加均线
ma5 = hist['close'].rolling(window=5).mean().bfill().tolist()
ma10 = hist['close'].rolling(window=10).mean().bfill().tolist()
ma20 = hist['close'].rolling(window=20).mean().bfill().tolist()

line_ma5 = (
    Line()
    .add_xaxis(dates)
    .add_yaxis("MA5", ma5, is_smooth=True, 
               linestyle_opts=opts.LineStyleOpts(width=2, color="#fbbf24"),
               label_opts=opts.LabelOpts(is_show=False))
)
line_ma10 = (
    Line()
    .add_xaxis(dates)
    .add_yaxis("MA10", ma10, is_smooth=True,
               linestyle_opts=opts.LineStyleOpts(width=2, color="#60a5fa"),
               label_opts=opts.LabelOpts(is_show=False))
)
line_ma20 = (
    Line()
    .add_xaxis(dates)
    .add_yaxis("MA20", ma20, is_smooth=True,
               linestyle_opts=opts.LineStyleOpts(width=2, color="#a78bfa"),
               label_opts=opts.LabelOpts(is_show=False))
)

kline.overlap(line_ma5)
kline.overlap(line_ma10)
kline.overlap(line_ma20)

# 保存K线图
kline.render(f"{output_dir}/kline_chart.html")
kline.render(f"{output_dir}/kline_chart.png")

# 2. 成交量图
volumes = hist['volume'].astype(float).tolist()
colors = ["#ef4444" if hist['close'].iloc[i] >= hist['open'].iloc[i] else "#22c55e" 
          for i in range(len(hist))]

bar = (
    Bar(init_opts=opts.InitOpts(width="1200px", height="300px", theme=ThemeType.DARK, bg_color="#1a1a2e"))
    .add_xaxis(dates)
    .add_yaxis("成交量", volumes, itemstyle_opts=opts.ItemStyleOpts(color=colors))
    .set_global_opts(
        title_opts=opts.TitleOpts(title="成交量", title_textstyle_opts=opts.TextStyleOpts(color="#fff")),
        xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate=45, color="#aaa")),
        yaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(color="#aaa"))
    )
)
bar.render(f"{output_dir}/volume_chart.html")
bar.render(f"{output_dir}/volume_chart.png")

# 3. 相关品种对比图
symbols = {'C0': '玉米', 'M0': '豆粕', 'CS0': '淀粉', 'LH0': '生猪'}
colors_map = {'C0': '#fbbf24', 'M0': '#60a5fa', 'CS0': '#a78bfa', 'LH0': '#f472b6'}

line_chart = (
    Line(init_opts=opts.InitOpts(
        width="1200px",
        height="600px",
        theme=ThemeType.DARK,
        bg_color="#1a1a2e"
    ))
    .set_global_opts(
        title_opts=opts.TitleOpts(
            title="相关品种价格走势对比",
            subtitle="归一化处理（基准=100）",
            title_textstyle_opts=opts.TextStyleOpts(color="#fff", font_size=20),
            pos_left="center"
        ),
        legend_opts=opts.LegendOpts(
            pos_top="10%",
            textstyle_opts=opts.TextStyleOpts(color="#fff", font_size=14)
        ),
        tooltip_opts=opts.TooltipOpts(trigger="axis"),
        xaxis_opts=opts.AxisOpts(
            type_="category",
            axislabel_opts=opts.LabelOpts(color="#aaa", rotate=45)
        ),
        yaxis_opts=opts.AxisOpts(
            type_="value",
            name="涨跌幅(%)",
            name_textstyle_opts=opts.TextStyleOpts(color="#aaa"),
            axislabel_opts=opts.LabelOpts(color="#aaa", formatter="{value}%"),
            splitline_opts=opts.SplitLineOpts(
                linestyle_opts=opts.LineStyleOpts(color="#333", type_="dashed")
            )
        )
    )
)

line_chart.add_xaxis(dates)

for code, name in symbols.items():
    try:
        df_sym = ak.futures_zh_daily_sina(symbol=code)
        df_sym = df_sym.tail(60).reset_index(drop=True)
        if len(df_sym) > 0:
            base_price = float(df_sym['close'].iloc[0])
            normalized = [(float(p) / base_price - 1) * 100 for p in df_sym['close']]
            line_chart.add_yaxis(
                name,
                normalized,
                is_smooth=True,
                symbol_size=0,
                linestyle_opts=opts.LineStyleOpts(width=3, color=colors_map[code]),
                label_opts=opts.LabelOpts(is_show=False)
            )
    except Exception as e:
        print(f"获取 {code} 数据失败: {e}")

line_chart.render(f"{output_dir}/correlation_chart.html")
line_chart.render(f"{output_dir}/correlation_chart.png")

print(f"✅ 图表生成完成！保存在: {output_dir}")
print(f"  - K线图: {output_dir}/kline_chart.html")
print(f"  - 成交量: {output_dir}/volume_chart.html")
print(f"  - 相关品种对比: {output_dir}/correlation_chart.html")
