fetch_a50.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import pandas as pd
  2. import akshare as ak
  3. from datetime import datetime, timedelta
  4. def fetch_a50_futures(period="30", days=60):
  5. """
  6. 获取富时中国A50指数期货数据 (SGX)
  7. Args:
  8. period: K线周期, "1"/"5"/"15"/"30"/"60"/"daily"
  9. days: 获取最近多少天的数据
  10. Returns:
  11. pd.DataFrame: 包含 Open/High/Low/Close/Volume 列, DateTime 为索引
  12. """
  13. print(f"正在获取富时中国A50期货 {period}分钟 K线数据...")
  14. # 方法1: 东方财富外盘期货接口
  15. try:
  16. # 富时A50连续合约代码
  17. df = ak.futures_foreign_hist_em(symbol="富时A50")
  18. if df is not None and not df.empty:
  19. df.rename(columns={
  20. '日期': 'DateTime', '开盘价': 'Open', '收盘价': 'Close',
  21. '最高价': 'High', '最低价': 'Low', '成交量': 'Volume',
  22. }, inplace=True)
  23. df['DateTime'] = pd.to_datetime(df['DateTime'])
  24. df.set_index('DateTime', inplace=True)
  25. df.sort_index(inplace=True)
  26. # 筛选时间范围
  27. cutoff = datetime.now() - timedelta(days=days)
  28. df = df[df.index >= cutoff].copy()
  29. print(f"[SUCCESS] 获取到 {len(df)} 条数据")
  30. print(f"数据范围: {df.index[0]} 至 {df.index[-1]}")
  31. return df[['Open', 'High', 'Low', 'Close', 'Volume']]
  32. except Exception as e:
  33. print(f"[ERROR] 东方财富接口失败: {e}")
  34. # 方法2: 新浪外盘期货
  35. try:
  36. df = ak.futures_foreign_detail_rb(symbol="A50")
  37. if df is not None and not df.empty:
  38. print(f"[SUCCESS] 新浪接口获取到 {len(df)} 条数据")
  39. return df
  40. except Exception as e:
  41. print(f"[ERROR] 新浪接口失败: {e}")
  42. raise ValueError("所有数据源均无法获取富时A50数据")
  43. if __name__ == "__main__":
  44. data = fetch_a50_futures()
  45. print(f"\n数据预览:")
  46. print(data.tail(10))