""" 测试 DataProvider """ import os import sys from datetime import datetime # 添加项目根目录到系统路径 project_root = os.path.dirname( os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ) sys.path.insert(0, project_root) from src.data_provider import DataProvider def test_get_klines(): """测试获取K线数据(DataFrame格式)""" print("\n" + "=" * 60) print("测试1: 获取K线数据(DataFrame格式)") print("=" * 60) symbols = ["000001.SZ", "600000.SH"] start_date = datetime(2024, 1, 1) end_date = datetime(2024, 12, 31) period = "1d" try: klines = DataProvider.get_klines( symbols=symbols, start_date=start_date, end_date=end_date, period=period, ) for symbol, df in klines.items(): print(f"\n股票: {symbol}") print(f"数据量: {len(df)} 根K线") if not df.empty: print(f"时间范围: {df.index[0]} ~ {df.index[-1]}") print(f"数据预览:\n{df.head()}") # 测试时间查询性能 target_date = "2024-06-15" if target_date in df.index: print(f"\n查询 {target_date} 的数据:") print(df.loc[target_date]) else: print(f"\n{target_date} 无数据") except Exception as e: print(f"❌ 测试失败: {e}") import traceback traceback.print_exc() def test_get_klines_pivot(): """测试获取宽表格式K线数据""" print("\n" + "=" * 60) print("测试2: 获取K线数据(宽表格式)") print("=" * 60) symbols = ["000001.SZ", "600000.SH"] start_date = datetime(2024, 1, 1) end_date = datetime(2024, 12, 31) period = "1d" try: df = DataProvider.get_klines_pivot( symbols=symbols, start_date=start_date, end_date=end_date, period=period, columns=["close", "volume"], ) print(f"数据量: {len(df)} 行") print(f"列: {df.columns.tolist()}") print(f"\n数据预览:\n{df.head()}") # 计算相关性 if "000001.SZ_close" in df.columns and "600000.SH_close" in df.columns: correlation = df[["000001.SZ_close", "600000.SH_close"]].corr() print(f"\n相关性矩阵:\n{correlation}") except Exception as e: print(f"❌ 测试失败: {e}") import traceback traceback.print_exc() def test_get_latest_kline(): """测试获取最新K线""" print("\n" + "=" * 60) print("测试3: 获取最新K线") print("=" * 60) symbols = ["000001.SZ", "600000.SH"] period = "1d" try: latest = DataProvider.get_latest_kline(symbols=symbols, period=period) for symbol, series in latest.items(): print(f"\n股票: {symbol}") if series is not None: print(f"时间: {series['timestamp']}") print( f"开高低收: {series['open']:.2f}, {series['high']:.2f}, " f"{series['low']:.2f}, {series['close']:.2f}" ) print(f"成交量: {series['volume']:.0f}") else: print("无数据") except Exception as e: print(f"❌ 测试失败: {e}") import traceback traceback.print_exc() def test_get_kline_range(): """测试获取最近N根K线""" print("\n" + "=" * 60) print("测试4: 获取最近N根K线") print("=" * 60) symbol = "000001.SZ" period = "1d" count = 20 try: df = DataProvider.get_kline_range(symbol=symbol, period=period, count=count) print(f"股票: {symbol}") print(f"数据量: {len(df)} 根K线") if not df.empty: print(f"时间范围: {df.index[0]} ~ {df.index[-1]}") print(f"\n数据预览:\n{df.head()}") # 计算均线 ma20 = df["close"].mean() print(f"\nMA{count}: {ma20:.2f}") # 计算滚动均线 df["MA5"] = df["close"].rolling(5).mean() df["MA10"] = df["close"].rolling(10).mean() print(f"\n带均线的数据:\n{df[['close', 'MA5', 'MA10']].tail()}") except Exception as e: print(f"❌ 测试失败: {e}") import traceback traceback.print_exc() def test_check_data_coverage(): """测试检查数据覆盖情况""" print("\n" + "=" * 60) print("测试5: 检查数据覆盖情况") print("=" * 60) symbols = ["000001.SZ", "600000.SH", "999999.SZ"] # 最后一个不存在 start_date = datetime(2024, 1, 1) end_date = datetime(2024, 12, 31) period = "1d" try: coverage = DataProvider.check_data_coverage( symbols=symbols, start_date=start_date, end_date=end_date, period=period, ) for symbol, info in coverage.items(): print(f"\n股票: {symbol}") if info["exists"]: print(f" ✓ 有数据") print(f" 开始日期: {info['start_date']}") print(f" 结束日期: {info['end_date']}") print(f" 数据量: {info['count']} 根K线") else: print(f" ✗ 无数据") print(f" 原因: {info.get('reason', 'unknown')}") except Exception as e: print(f"❌ 测试失败: {e}") import traceback traceback.print_exc() def test_get_available_info(): """测试获取可用的股票和周期""" print("\n" + "=" * 60) print("测试6: 获取可用的股票和周期") print("=" * 60) try: # 获取所有股票 symbols = DataProvider.get_available_symbols() print(f"可用股票: {len(symbols)} 只") print(f"前10只: {symbols[:10]}") # 获取某只股票的周期 if symbols: symbol = symbols[0] periods = DataProvider.get_available_periods(symbol) print(f"\n{symbol} 的可用周期: {periods}") except Exception as e: print(f"❌ 测试失败: {e}") import traceback traceback.print_exc() def test_conversion(): """测试 DataFrame 和 Kline 对象转换""" print("\n" + "=" * 60) print("测试7: DataFrame 和 Kline 对象转换") print("=" * 60) symbol = "000001.SZ" start_date = datetime(2024, 1, 1) end_date = datetime(2024, 1, 10) period = "1d" try: # 获取 DataFrame klines_dict = DataProvider.get_klines( symbols=[symbol], start_date=start_date, end_date=end_date, period=period ) df = klines_dict[symbol] print(f"原始 DataFrame: {len(df)} 行") print(df.head()) if df.empty: print("⚠️ 数据为空,跳过转换测试") return # DataFrame -> Kline 对象列表 kline_objects = DataProvider.dataframe_to_klines(df, symbol, period) print(f"\n转换为 Kline 对象: {len(kline_objects)} 个") print(f"第一个对象: {kline_objects[0]}") # Kline 对象列表 -> DataFrame df_converted = DataProvider.klines_to_dataframe(kline_objects) print(f"\n转换回 DataFrame: {len(df_converted)} 行") print(df_converted.head()) # 验证数据一致性 if len(df) == len(df_converted): print("\n✓ 数据长度一致") else: print(f"\n✗ 数据长度不一致: {len(df)} vs {len(df_converted)}") except Exception as e: print(f"❌ 测试失败: {e}") import traceback traceback.print_exc() if __name__ == "__main__": print("\n" + "=" * 60) print("开始测试 DataProvider") print("=" * 60) test_get_klines() test_get_klines_pivot() test_get_latest_kline() test_get_kline_range() test_check_data_coverage() test_get_available_info() test_conversion() print("\n" + "=" * 60) print("所有测试完成") print("=" * 60)