#!/usr/bin/env python3
"""
玉米期货投研PPT图表生成脚本
"""

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('Agg')
import numpy as np

# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei', 'DejaVu Sans', 'WenQuanYi Micro Hei', 'Arial Unicode MS']
plt.rcParams['axes.unicode_minus'] = False

# 投研风格配色
COLORS = {
    'blue': '#1a365d',
    'gold': '#d69e2e',
    'red': '#c53030',
    'green': '#2f855a',
    'gray': '#718096',
    'light_blue': '#3182ce',
    'bg': '#f7fafc'
}

def load_data():
    """加载数据"""
    corn = pd.read_csv('/root/.openclaw/workspace/corn_data.csv')
    meal = pd.read_csv('/root/.openclaw/workspace/meal_data.csv')
    starch = pd.read_csv('/root/.openclaw/workspace/starch_data.csv')
    hog = pd.read_csv('/root/.openclaw/workspace/hog_data.csv')
    return corn, meal, starch, hog

def create_price_chart(corn):
    """生成玉米价格走势图"""
    fig, ax = plt.subplots(figsize=(12, 6))
    ax.set_facecolor(COLORS['bg'])
    
    dates = pd.to_datetime(corn['date'])
    closes = corn['close'].values
    
    # 绘制K线图简化版（收盘价曲线）
    ax.plot(dates, closes, color=COLORS['blue'], linewidth=2, label='收盘价')
    ax.fill_between(dates, closes, min(closes)*0.98, alpha=0.3, color=COLORS['light_blue'])
    
    # 添加均线
    corn['ma5'] = corn['close'].rolling(5).mean()
    corn['ma10'] = corn['close'].rolling(10).mean()
    corn['ma20'] = corn['close'].rolling(20).mean()
    
    ax.plot(dates, corn['ma5'], color=COLORS['gold'], linewidth=1, linestyle='--', label='MA5')
    ax.plot(dates, corn['ma10'], color=COLORS['red'], linewidth=1, linestyle='--', label='MA10')
    ax.plot(dates, corn['ma20'], color=COLORS['green'], linewidth=1, linestyle='--', label='MA20')
    
    ax.set_title('玉米期货主力合约价格走势（60日）', fontsize=16, fontweight='bold', color=COLORS['blue'])
    ax.set_xlabel('日期', fontsize=12)
    ax.set_ylabel('价格（元/吨）', fontsize=12)
    ax.legend(loc='upper left')
    ax.grid(True, alpha=0.3)
    
    plt.tight_layout()
    plt.savefig('/root/.openclaw/workspace/ppt_images/chart1_price.png', dpi=150, bbox_inches='tight')
    plt.close()
    print("✅ 图表1: 价格走势图 完成")

def create_volume_chart(corn):
    """生成持仓量变化图"""
    fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 8), gridspec_kw={'height_ratios': [2, 1]})
    
    dates = pd.to_datetime(corn['date'])
    
    # 持仓量
    ax1.bar(dates, corn['hold']/10000, color=COLORS['light_blue'], alpha=0.7)
    ax1.set_title('持仓量变化（60日）', fontsize=14, fontweight='bold', color=COLORS['blue'])
    ax1.set_ylabel('持仓量（万手）', fontsize=11)
    ax1.grid(True, alpha=0.3, axis='y')
    
    # 成交量
    ax2.bar(dates, corn['volume']/10000, color=COLORS['gold'], alpha=0.7)
    ax2.set_title('成交量变化（60日）', fontsize=14, fontweight='bold', color=COLORS['blue'])
    ax2.set_xlabel('日期', fontsize=11)
    ax2.set_ylabel('成交量（万手）', fontsize=11)
    ax2.grid(True, alpha=0.3, axis='y')
    
    plt.tight_layout()
    plt.savefig('/root/.openclaw/workspace/ppt_images/chart2_volume.png', dpi=150, bbox_inches='tight')
    plt.close()
    print("✅ 图表2: 持仓量/成交量图 完成")

def create_correlation_chart(corn, meal, starch, hog):
    """生成相关品种对比图"""
    fig, axes = plt.subplots(2, 2, figsize=(14, 10))
    
    # 归一化数据（以第一个值为基准）
    def normalize(series):
        return series / series.iloc[0] * 100
    
    dates = pd.to_datetime(corn['date'])
    
    # 玉米
    ax1 = axes[0, 0]
    ax1.plot(dates, normalize(corn['close']), color=COLORS['blue'], linewidth=2)
    ax1.set_title('玉米期货', fontsize=14, fontweight='bold')
    ax1.set_ylabel('价格指数', fontsize=11)
    ax1.grid(True, alpha=0.3)
    ax1.axhline(y=100, color='gray', linestyle='--', alpha=0.5)
    
    # 豆粕
    ax2 = axes[0, 1]
    ax2.plot(dates, normalize(meal['close']), color=COLORS['red'], linewidth=2)
    ax2.set_title('豆粕期货', fontsize=14, fontweight='bold')
    ax2.set_ylabel('价格指数', fontsize=11)
    ax2.grid(True, alpha=0.3)
    ax2.axhline(y=100, color='gray', linestyle='--', alpha=0.5)
    
    # 淀粉
    ax3 = axes[1, 0]
    ax3.plot(dates, normalize(starch['close']), color=COLORS['gold'], linewidth=2)
    ax3.set_title('淀粉期货', fontsize=14, fontweight='bold')
    ax3.set_xlabel('日期', fontsize=11)
    ax3.set_ylabel('价格指数', fontsize=11)
    ax3.grid(True, alpha=0.3)
    ax3.axhline(y=100, color='gray', linestyle='--', alpha=0.5)
    
    # 生猪
    ax4 = axes[1, 1]
    ax4.plot(dates, normalize(hog['close']), color=COLORS['green'], linewidth=2)
    ax4.set_title('生猪期货', fontsize=14, fontweight='bold')
    ax4.set_xlabel('日期', fontsize=11)
    ax4.set_ylabel('价格指数', fontsize=11)
    ax4.grid(True, alpha=0.3)
    ax4.axhline(y=100, color='gray', linestyle='--', alpha=0.5)
    
    plt.suptitle('相关品种价格走势对比（归一化）', fontsize=16, fontweight='bold', color=COLORS['blue'], y=1.02)
    plt.tight_layout()
    plt.savefig('/root/.openclaw/workspace/ppt_images/chart3_correlation.png', dpi=150, bbox_inches='tight')
    plt.close()
    print("✅ 图表3: 相关品种对比图 完成")

def create_summary_table(corn):
    """生成关键数据汇总"""
    latest = corn.iloc[-1]
    prev = corn.iloc[-5] if len(corn) >= 5 else corn.iloc[0]
    
    data = {
        '指标': ['最新收盘价', '60日最高', '60日最低', 'MA5', 'MA10', 'MA20', '最新持仓', '周涨幅', '月涨幅'],
        '数值': [
            f'{latest["close"]:.0f}元/吨',
            f'{corn["high"].max():.0f}元/吨',
            f'{corn["low"].min():.0f}元/吨',
            f'{corn["close"].tail(5).mean():.1f}元/吨',
            f'{corn["close"].tail(10).mean():.1f}元/吨',
            f'{corn["close"].tail(20).mean():.1f}元/吨',
            f'{latest["hold"]/10000:.1f}万手',
            f'{(latest["close"]/prev["close"]-1)*100:.2f}%',
            f'{(latest["close"]/corn.iloc[0]["close"]-1)*100:.2f}%'
        ]
    }
    
    df = pd.DataFrame(data)
    fig, ax = plt.subplots(figsize=(10, 4))
    ax.axis('off')
    
    table = ax.table(cellText=df.values, colLabels=df.columns, 
                     cellLoc='center', loc='center',
                     colColours=[COLORS['blue']]*2)
    table.auto_set_font_size(False)
    table.set_fontsize(12)
    table.scale(1.2, 2)
    
    # 设置表头颜色
    for i in range(2):
        table[(0, i)].set_text_props(color='white', fontweight='bold')
    
    plt.title('玉米期货关键数据汇总', fontsize=16, fontweight='bold', color=COLORS['blue'], pad=20)
    plt.tight_layout()
    plt.savefig('/root/.openclaw/workspace/ppt_images/chart4_summary.png', dpi=150, bbox_inches='tight')
    plt.close()
    print("✅ 图表4: 关键数据汇总表 完成")

def main():
    import os
    os.makedirs('/root/.openclaw/workspace/ppt_images', exist_ok=True)
    
    print("📊 开始生成图表...")
    corn, meal, starch, hog = load_data()
    
    create_price_chart(corn)
    create_volume_chart(corn)
    create_correlation_chart(corn, meal, starch, hog)
    create_summary_table(corn)
    
    print("\n✅ 所有图表生成完成！")
    print("📁 图表保存在: /root/.openclaw/workspace/ppt_images/")

if __name__ == '__main__':
    main()
