import pandas as pd
import akshare as ak
from datetime import datetime, timedelta


def fetch_a50_futures(period="30", days=60):
    """
    获取富时中国A50指数期货数据 (SGX)

    Args:
        period: K线周期, "1"/"5"/"15"/"30"/"60"/"daily"
        days: 获取最近多少天的数据

    Returns:
        pd.DataFrame: 包含 Open/High/Low/Close/Volume 列, DateTime 为索引
    """
    print(f"正在获取富时中国A50期货 {period}分钟 K线数据...")

    # 方法1: 东方财富外盘期货接口
    try:
        # 富时A50连续合约代码
        df = ak.futures_foreign_hist_em(symbol="富时A50")
        if df is not None and not df.empty:
            df.rename(columns={
                '日期': 'DateTime', '开盘价': 'Open', '收盘价': 'Close',
                '最高价': 'High', '最低价': 'Low', '成交量': 'Volume',
            }, inplace=True)
            df['DateTime'] = pd.to_datetime(df['DateTime'])
            df.set_index('DateTime', inplace=True)
            df.sort_index(inplace=True)

            # 筛选时间范围
            cutoff = datetime.now() - timedelta(days=days)
            df = df[df.index >= cutoff].copy()

            print(f"[SUCCESS] 获取到 {len(df)} 条数据")
            print(f"数据范围: {df.index[0]} 至 {df.index[-1]}")
            return df[['Open', 'High', 'Low', 'Close', 'Volume']]
    except Exception as e:
        print(f"[ERROR] 东方财富接口失败: {e}")

    # 方法2: 新浪外盘期货
    try:
        df = ak.futures_foreign_detail_rb(symbol="A50")
        if df is not None and not df.empty:
            print(f"[SUCCESS] 新浪接口获取到 {len(df)} 条数据")
            return df
    except Exception as e:
        print(f"[ERROR] 新浪接口失败: {e}")

    raise ValueError("所有数据源均无法获取富时A50数据")


if __name__ == "__main__":
    data = fetch_a50_futures()
    print(f"\n数据预览:")
    print(data.tail(10))
