repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
TradingAgents-CN | tests/test_final_config.py | .py | #!/usr/bin/env python3
"""
测试最终的.env配置系统
验证启用开关是否正常工作
"""
import os
def test_final_config():
"""测试最终配置"""
print("🔧 测试最终的.env配置系统")
print("=" * 40)
# 1. 检查.env文件
print("\n📁 检查.env文件...")
if os.path.exists('.env'):
print("✅ .env文件存在")
else:
print("❌ .env文件不存在")
... | 156 | 5,305 |
TradingAgents-CN | tests/test_correct_apis.py | .py | #!/usr/bin/env python3
"""
正确测试Google和Reddit API工具
"""
import os
import sys
from pathlib import Path
from dotenv import load_dotenv
# 添加项目根目录到Python路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))
# 加载环境变量
load_dotenv(project_root / ".env", override=True)
def test_google_news_tool():
... | 215 | 7,627 |
TradingAgents-CN | tests/conftest.py | .py | import os
import sys
# 将项目根目录加入 sys.path,确保 `import tradingagents` 可用
PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
if PROJECT_ROOT not in sys.path:
sys.path.insert(0, PROJECT_ROOT)
| 9 | 246 |
TradingAgents-CN | tests/test_hk_improved.py | .py | """
改进的港股功能测试
"""
import sys
import os
# 添加项目根目录到路径
project_root = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, project_root)
def test_stock_recognition():
"""测试股票识别功能"""
print("🧪 测试股票识别功能...")
try:
from tradingagents.utils.stock_utils import StockUtils
tes... | 199 | 6,610 |
TradingAgents-CN | tests/integration/test_dashscope_integration.py | .py | #!/usr/bin/env python3
"""
阿里百炼大模型集成测试脚本
用于验证 TradingAgents 中的阿里百炼集成是否正常工作
"""
import os
import sys
from pathlib import Path
# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent.parent
sys.path.insert(0, str(project_root))
from dotenv import load_dotenv
# 加载 .env 文件
load_dotenv()
def test_import():
"... | 180 | 5,558 |
TradingAgents-CN | tests/test_tushare_unified/test_tushare_sync_service.py | .py | """
测试TushareSyncService
"""
import pytest
import asyncio
from unittest.mock import Mock, patch, AsyncMock
from datetime import datetime, timedelta
from app.worker.tushare_sync_service import TushareSyncService
class TestTushareSyncService:
"""测试TushareSyncService类"""
@pytest.fixture
def sync_servic... | 292 | 11,068 |
TradingAgents-CN | tests/test_tushare_unified/test_tushare_provider.py | .py | """
测试统一的TushareProvider
"""
import pytest
import asyncio
from unittest.mock import Mock, patch, AsyncMock
from datetime import datetime, date
import pandas as pd
from tradingagents.dataflows.providers.tushare_provider import TushareProvider
class TestTushareProvider:
"""测试TushareProvider类"""
@pytest.fi... | 277 | 10,681 |
TradingAgents-CN | tests/test_tushare_unified/__init__.py | .py | """
Tushare统一方案测试包
"""
| 4 | 37 |
TradingAgents-CN | tests/services/test_scheduler_quotes_job.py | .py | import inspect
from types import SimpleNamespace
from apscheduler.triggers.interval import IntervalTrigger
from fastapi import FastAPI
def test_scheduler_adds_quotes_job(monkeypatch):
# Flags to assert behavior
state = SimpleNamespace(
ensure_indexes_called=False,
create_task_called=False,
... | 99 | 3,267 |
TradingAgents-CN | tests/services/test_screening_roe_field.py | .py | import asyncio
def test_database_screening_builds_roe_query():
from app.services.database_screening_service import DatabaseScreeningService
svc = DatabaseScreeningService()
async def _run():
query = await svc._build_query([
{"field": "roe", "operator": "between", "value": [10, 20]},
... | 79 | 2,376 |
TradingAgents-CN | tests/services/test_quotes_ingestion_and_enrichment.py | .py | import asyncio
from typing import Any, Dict, List
def test_enhanced_screening_enriches_from_db(monkeypatch):
# Late import to patch module symbols correctly
from app.services.enhanced_screening_service import EnhancedScreeningService
# Fake DB layer
class FakeCursor:
def __init__(self, docs: ... | 136 | 4,582 |
TradingAgents-CN | tests/services/test_quotes_backfill.py | .py | import asyncio
def test_offhours_backfill_when_empty(monkeypatch):
from app.services.quotes_ingestion_service import QuotesIngestionService
import app.services.quotes_ingestion_service as qis_mod
# Fake DataSourceManager to avoid external calls
class _FakeManager:
def get_realtime_quotes_with... | 66 | 2,006 |
TradingAgents-CN | tests/dataflows/test_realtime_metrics.py | .py | """
测试实时PE/PB计算功能
"""
import pytest
from tradingagents.dataflows.realtime_metrics import (
calculate_realtime_pe_pb,
validate_pe_pb,
get_pe_pb_with_fallback
)
def test_validate_pe_pb():
"""测试PE/PB验证"""
# 正常范围
assert validate_pe_pb(20.5, 3.2) == True
assert validate_pe_pb(50, 2.5) == True
... | 170 | 5,013 |
TradingAgents-CN | tests/config/test_settings.py | .py | from app.core.config import Settings
def test_settings_defaults_and_env_override(monkeypatch):
# Override a few env vars
monkeypatch.setenv("PORT", "8123")
monkeypatch.setenv("DEBUG", "false")
monkeypatch.setenv("MONGODB_USERNAME", "user")
monkeypatch.setenv("MONGODB_PASSWORD", "pass")
monkeyp... | 42 | 1,336 |
TradingAgents-CN | tests/config/test_logging_config.py | .py | import os
from importlib import reload
from pathlib import Path
import pytest
MINIMAL_TOML = """
[logging]
level = "INFO"
[logging.format]
console = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
file = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
[logging.handlers.file]
directory = "./logs"
leve... | 57 | 1,546 |
TradingAgents-CN | tests/config/test_deprecations.py | .py | import importlib
import warnings
def test_legacy_env_aliases_map_to_new(monkeypatch):
# Ensure new keys are not set so aliasing triggers
monkeypatch.delenv("HOST", raising=False)
monkeypatch.delenv("PORT", raising=False)
monkeypatch.delenv("DEBUG", raising=False)
# Set only legacy keys
monkey... | 31 | 1,010 |
TradingAgents-CN | tests/config/test_logging_json.py | .py | from importlib import reload
import logging
def test_json_console_formatter_enabled(monkeypatch, tmp_path):
# Arrange: TOML with json flag
cfg_dir = tmp_path / "config"
cfg_dir.mkdir(parents=True, exist_ok=True)
(cfg_dir / "logging.toml").write_text(
"""
[logging]
level = "INFO"
[logging.form... | 38 | 993 |
TradingAgents-CN | tests/unit/test_stocks_kline_news_api.py | .py | import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from unittest.mock import patch
# Build a minimal app that mounts only the stocks router to avoid triggering app.main lifespan
from app.routers import stocks as stocks_router
from app.routers.auth import get_current_user
def create_t... | 77 | 3,048 |
TradingAgents-CN | tests/unit/tools/analysis/test_indicators_uil.py | .py | import math
import pandas as pd
import numpy as np
from tradingagents.tools.analysis.indicators import (
IndicatorSpec,
compute_many,
)
def make_df(n=60, seed=42):
rng = np.random.default_rng(seed)
close = pd.Series(np.cumsum(rng.normal(0, 1, n)) + 100)
high = close + rng.uniform(0, 2, n)
low... | 51 | 1,613 |
TradingAgents-CN | tests/unit/dataflows/test_unified_dataframe.py | .py | import pandas as pd
from unittest import mock
from tradingagents.dataflows.unified_dataframe import get_china_daily_df_unified
def test_unified_dataframe_prefers_tushare_then_akshare_then_baostock():
# 模拟三个来源:tushare成功,后两个不应被调用
with mock.patch('tradingagents.dataflows.unified_dataframe.get_tushare_adapter') ... | 53 | 2,621 |
TradingAgents-CN | tests/middleware/test_trace_id.py | .py | import re
import logging
import io
from fastapi import FastAPI
from fastapi.testclient import TestClient
from app.middleware.request_id import RequestIDMiddleware
from app.core.logging_config import setup_logging
from app.core.logging_context import LoggingContextFilter
UUID_RE = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4... | 59 | 1,564 |
TradingAgents-CN | tests/0.1.14/test_data_structure.py | .py | #!/usr/bin/env python3
"""
测试数据结构脚本
"""
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), 'web'))
def test_data_structure():
"""测试分析结果数据结构"""
try:
from web.components.analysis_results import load_analysis_results
print("🔍 测试分析结果数据结构...")
# ... | 54 | 1,830 |
TradingAgents-CN | tests/0.1.14/test_google_tool_handler_fix.py | .py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
测试Google工具调用处理器修复效果
"""
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from tradingagents.agents.utils.google_tool_handler import GoogleToolCallHandler
import logging
# 设置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)... | 176 | 6,268 |
TradingAgents-CN | tests/0.1.14/test_tool_selection_logic.py | .py | #!/usr/bin/env python3
"""
测试新的工具选择逻辑
验证美股数据获取不再依赖OpenAI配置
"""
import os
import sys
from pathlib import Path
# 添加项目根目录到路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))
def test_tool_selection_scenarios():
"""测试不同配置场景下的工具选择"""
print("🧪 测试工具选择逻辑")
print("=" * 70)
scen... | 272 | 9,726 |
TradingAgents-CN | tests/0.1.14/test_online_tools_config.py | .py | #!/usr/bin/env python3
"""
测试新的在线工具配置系统
验证环境变量和配置文件的集成
"""
import os
import sys
from pathlib import Path
# 添加项目根目录到Python路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))
def test_online_tools_config():
"""测试在线工具配置"""
print("🧪 测试在线工具配置系统")
print("=" * 60)
# 1. 检查环境变量... | 173 | 5,964 |
TradingAgents-CN | tests/0.1.14/cleanup_test_data.py | .py | #!/usr/bin/env python3
"""
清理测试数据
"""
import sys
import os
from pathlib import Path
# 添加项目路径
sys.path.append(os.path.join(os.path.dirname(__file__), 'web'))
def cleanup_test_files():
"""清理测试文件"""
print("🧹 清理测试文件...")
# 清理详细报告目录
project_root = Path(__file__).parent
test_dir = project_root / ... | 64 | 1,719 |
TradingAgents-CN | tests/0.1.14/test_us_stock_independence.py | .py | #!/usr/bin/env python3
"""
测试美股数据获取独立性
验证美股数据获取不再依赖OpenAI配置
"""
import os
import sys
from pathlib import Path
# 添加项目根目录到路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))
try:
from tradingagents.agents.utils.agent_utils import Toolkit
from tradingagents.default_config import DEFAUL... | 97 | 3,078 |
TradingAgents-CN | tests/0.1.14/test_guide_auto_hide.py | .py | #!/usr/bin/env python3
"""
测试使用指南自动隐藏功能
验证在开始分析时使用指南会自动隐藏
"""
import sys
from pathlib import Path
# 添加项目根目录到路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))
def test_guide_auto_hide_logic():
"""测试使用指南自动隐藏逻辑"""
print("📖 测试使用指南自动隐藏功能")
print("=" * 60)
# 模拟session stat... | 210 | 8,066 |
TradingAgents-CN | tests/0.1.14/test_real_scenario_fix.py | .py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
实际场景测试:验证Google工具调用处理器修复效果
"""
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from tradingagents.default_config import DEFAULT_CONFIG
from tradingagents.agents.utils.google_tool_handler import GoogleToolCallHandler
import logging
# ... | 235 | 8,788 |
TradingAgents-CN | tests/0.1.14/create_sample_reports.py | .py | #!/usr/bin/env python3
"""
创建示例分析报告
用于测试Web界面的报告显示功能
"""
import sys
import os
from datetime import datetime
# 添加项目路径
sys.path.append(os.path.join(os.path.dirname(__file__), 'web'))
def create_sample_report(stock_symbol: str, stock_name: str):
"""创建示例分析报告"""
# 分析结果数据
analysis_results = {
"sum... | 186 | 5,137 |
TradingAgents-CN | tests/0.1.14/test_analysis_save.py | .py | #!/usr/bin/env python3
"""
测试分析结果保存功能
模拟分析完成后的保存过程
"""
import sys
import os
from datetime import datetime
# 添加项目路径
sys.path.append(os.path.join(os.path.dirname(__file__), 'web'))
def create_mock_analysis_results():
"""创建模拟的分析结果数据"""
return {
'stock_symbol': 'TEST123',
'analysis_date': '2025-0... | 210 | 6,705 |
TradingAgents-CN | tests/tradingagents/test_app_cache_toggle.py | .py | import os
import types
import builtins
import pandas as pd
import pytest
from typing import Any, Dict, Optional
class DummyDBManager:
def __init__(self, available: bool = True):
self._available = available
def is_mongodb_available(self) -> bool:
return self._available
def get_mongodb_cl... | 173 | 6,082 |
TradingAgents-CN | tests/system/test_llm_provider_sanitization.py | .py | import sys
from pathlib import Path
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
# Ensure project root on path
PROJECT_ROOT = Path(__file__).resolve().parents[1]
if str(PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(PROJECT_ROOT))
from app.routers import config as co... | 99 | 3,024 |
TradingAgents-CN | tests/system/test_config_summary.py | .py | import io
import json
import logging
from fastapi.testclient import TestClient
from app.main import app
from app.services.auth_service import AuthService
def _auth_headers() -> dict:
token = AuthService.create_access_token(sub="admin")
return {"Authorization": f"Bearer {token}"}
def test_config_summary_req... | 59 | 1,764 |
TradingAgents-CN | scripts/convert_prints_to_logs.py | .py | #!/usr/bin/env python3
"""
将项目中的print语句转换为日志输出
排除tests和env目录
"""
import os
import re
from pathlib import Path
from typing import List, Dict, Tuple
class PrintToLogConverter:
"""Print语句到日志转换器"""
def __init__(self, project_root: Path):
self.project_root = project_root
self.converted_files ... | 308 | 10,680 |
TradingAgents-CN | scripts/verify_imported_config.py | .py | #!/usr/bin/env python3
"""
验证导入后的配置数据
使用方法:
# 在测试服务器的 Docker 容器内运行
docker exec tradingagents-backend python /tmp/verify_imported_config.py
"""
import sys
from pymongo import MongoClient
# MongoDB 连接配置(Docker 容器内)
MONGO_URI = "mongodb://admin:tradingagents123@mongodb:27017/tradingagents?authSource=admin"
DB_N... | 123 | 4,227 |
TradingAgents-CN | scripts/migrate_config.py | .py | #!/usr/bin/env python3
"""
配置迁移工具
将现有的配置文件迁移到统一配置管理系统
"""
import sys
import os
import json
from pathlib import Path
# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
from webapi.core.unified_config import unified_config
from webapi.models.config import SystemConfig
... | 235 | 7,279 |
TradingAgents-CN | scripts/init_paper_trading_market_rules.py | .py | """
初始化模拟交易市场规则配置
运行方式:
python scripts/init_paper_trading_market_rules.py
"""
import asyncio
import sys
from pathlib import Path
# 添加项目根目录到 Python 路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
from app.core.database import get_mongo_db, init_database
# 市场规则配置
MARKET_RULE... | 261 | 9,251 |
TradingAgents-CN | scripts/test_akshare_batch_quotes.py | .py | #!/usr/bin/env python3
"""测试 AKShare 批量获取行情功能"""
import asyncio
import sys
from pathlib import Path
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
from app.core.database import init_database
from tradingagents.dataflows.providers.china.akshare import AKShareProvider
async def mai... | 60 | 1,657 |
TradingAgents-CN | scripts/migrate_financial_data_symbol_to_code.py | .py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
将 stock_financial_data 集合的 symbol 字段统一改为 code
背景:
- stock_basic_info 使用 code 字段(6位数字)
- stock_financial_data 使用 symbol 字段(6位数字)
- 为了统一,将 symbol 改为 code
步骤:
1. 为所有文档添加 code 字段(值为 symbol)
2. 删除 symbol 字段
3. 为 code 字段创建索引
"""
import asyncio
import sys
import os
sys.path... | 115 | 3,866 |
TradingAgents-CN | scripts/akshare_sync_optimized.py | .py | #!/usr/bin/env python3
"""
AKShare 优化同步脚本
优化点:
1. 预先缓存股票列表,避免重复获取
2. 批量处理,显示详细进度
3. 失败重试机制
4. 详细的错误日志
使用方法:
python scripts/akshare_sync_optimized.py
python scripts/akshare_sync_optimized.py --batch-size 100 # 调整批次大小
python scripts/akshare_sync_optimized.py --delay 0.2 # 调整延迟时间
"""
import asyncio
import... | 254 | 8,876 |
TradingAgents-CN | scripts/sync_financial_data.py | .py | #!/usr/bin/env python3
"""
同步股票财务数据
功能:
1. 从 AKShare 获取股票财务指标
2. 更新 stock_basic_info 集合的财务字段
3. 创建/更新 stock_financial_data 集合
使用方法:
python scripts/sync_financial_data.py 600036 # 同步单只股票
python scripts/sync_financial_data.py --all # 同步所有股票
python scripts/sync_financial_data.py --batch 100 # 批量同步前100只
"... | 440 | 16,359 |
TradingAgents-CN | scripts/test_api_key_edit.py | .py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
测试 API Key 编辑功能
测试场景:
1. 添加新厂家并配置 API Key
2. 更新厂家的 API Key
3. 清空厂家的 API Key(使用环境变量)
4. 验证配置优先级
"""
import sys
import os
from pathlib import Path
# 添加项目根目录到 Python 路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
import asyncio
fr... | 228 | 6,708 |
TradingAgents-CN | scripts/unified_data_manager.py | .py | #!/usr/bin/env python3
"""
统一数据目录配置管理器
Unified Data Directory Configuration Manager
提供统一的数据目录配置管理功能
"""
import os
from pathlib import Path
from typing import Dict, Optional, Union
import logging
logger = logging.getLogger(__name__)
class UnifiedDataDirectoryManager:
"""统一数据目录管理器"""
def __init__(self, p... | 301 | 10,047 |
TradingAgents-CN | scripts/test_direct_mongodb.py | .py | """
直接测试 MongoDB 读取
"""
import sys
from pathlib import Path
# 添加项目根目录到路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
from pymongo import MongoClient
from app.core.config import settings
def test_direct():
"""直接测试"""
print("=" * 80)
print("直接测试 MongoDB 读取")
... | 83 | 2,701 |
TradingAgents-CN | scripts/update_db_api_keys.py | .py | #!/usr/bin/env python3
"""
更新数据库中的 API Key
从 .env 文件读取真实的 API Key,更新到 MongoDB 数据库中
"""
import asyncio
import os
import sys
from pathlib import Path
from dotenv import load_dotenv
# 添加项目根目录到 Python 路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
# 加载 .env 文件
env_file = project_roo... | 174 | 6,097 |
TradingAgents-CN | scripts/test_env_validation.py | .py | """
测试 .env 文件中的 API Key 验证
验证占位符是否被正确识别为"未配置"
"""
import sys
import os
from pathlib import Path
# 添加项目根目录到 Python 路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
# 加载 .env 文件
from dotenv import load_dotenv
load_dotenv(project_root / ".env")
from app.core.startup_validator impo... | 119 | 3,652 |
TradingAgents-CN | scripts/test_provider_lookup.py | .py | """
测试供应商查找功能
"""
import sys
from pathlib import Path
# 添加项目根目录到路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
from app.services.simple_analysis_service import get_provider_and_url_by_model_sync
def test_provider_lookup():
"""测试供应商和 URL 查找(同步版本)"""
test_models = [
... | 39 | 950 |
TradingAgents-CN | scripts/fix_logger_position.py | .py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
修复logger变量位置脚本 (改进版)
Fix logger variable position script (improved version)
将错误位置的logger初始化移动到文件头部import语句下面
Move misplaced logger initialization to the correct position after import statements
"""
import os
import re
import sys
from typing import List, Tuple, Option... | 276 | 10,057 |
TradingAgents-CN | scripts/fix_stock_code_issue.py | .py | #!/usr/bin/env python3
"""
修复股票代码误判问题的脚本
"""
import os
import shutil
import sys
# 导入日志模块
from tradingagents.utils.logging_manager import get_logger
logger = get_logger('default')
def clear_all_caches():
"""清理所有缓存"""
logger.info(f"🧹 清理所有缓存...")
cache_dirs = [
"tradingagents/dataflows/data_ca... | 194 | 6,347 |
TradingAgents-CN | scripts/test_config_bridge.py | .py | #!/usr/bin/env python3
"""
测试配置桥接功能
验证数据库配置是否正确桥接到环境变量
"""
import os
import sys
import asyncio
from pathlib import Path
# 添加项目根目录到 Python 路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
async def test_config_bridge():
"""测试配置桥接"""
print("=" * 60)
print("🧪 测试配置桥接功能")
... | 174 | 5,315 |
TradingAgents-CN | scripts/enable_mongodb_cache.py | .py | #!/usr/bin/env python3
"""启用MongoDB缓存并测试"""
import sys
import os
from pathlib import Path
# 添加项目根目录到 Python 路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
print("=" * 80)
print("🔧 启用 MongoDB 缓存")
print("=" * 80)
# 1. 检查 .env 文件
env_file = project_root / ".env"
print(f"\n1️⃣ 检查... | 140 | 4,200 |
TradingAgents-CN | scripts/test_api_key_validation.py | .py | """
测试 API Key 验证逻辑
验证占位符检测是否正常工作
"""
import sys
import os
from pathlib import Path
# 添加项目根目录到 Python 路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
from app.core.startup_validator import StartupValidator
def test_api_key_validation():
"""测试 API Key 验证逻辑"""
validator ... | 77 | 2,819 |
TradingAgents-CN | scripts/test_akshare_rate_limit.py | .py | """
测试 AKShare 请求频率限制
验证东方财富接口的最佳请求间隔
"""
import time
import akshare as ak
from datetime import datetime
import sys
def test_single_request():
"""测试单次请求"""
print("=" * 70)
print("📊 测试单次请求")
print("=" * 70)
try:
start_time = time.time()
df = ak.stock_zh_a_spot_em()
el... | 300 | 11,025 |
TradingAgents-CN | scripts/check_datasource_names.py | .py | #!/usr/bin/env python3
"""检查数据库中数据源配置的名称"""
import sys
from pathlib import Path
# 添加项目根目录到 Python 路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
from app.core.database import get_mongo_db_sync
import json
db = get_mongo_db_sync()
# 先列出所有集合
print("📋 数据库中的集合:")
for collection_n... | 57 | 1,547 |
TradingAgents-CN | scripts/test_config_compatibility.py | .py | #!/usr/bin/env python3
"""
配置兼容性测试脚本
测试统一配置管理系统与现有系统的兼容性
"""
import sys
import os
import json
import asyncio
from pathlib import Path
# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
from webapi.core.unified_config import unified_config
from webapi.models.config im... | 298 | 9,361 |
TradingAgents-CN | scripts/migrate_data_directories.py | .py | #!/usr/bin/env python3
"""
数据目录重新组织迁移脚本
Data Directory Reorganization Migration Script
此脚本将项目中分散的数据目录重新组织为统一的结构
"""
import os
import shutil
import json
from pathlib import Path
from typing import Dict, List, Tuple
import logging
from datetime import datetime
# 设置日志
os.makedirs(os.path.join('data', 'logs'), exist_ok=... | 350 | 13,496 |
TradingAgents-CN | scripts/quick_test_pe_pb.py | .py | #!/usr/bin/env python3
"""
快速测试 PE/PB 修复
使用方法:
python scripts/quick_test_pe_pb.py 600036
"""
import sys
from pathlib import Path
# 添加项目根目录到路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
import logging
# 配置日志
logging.basicConfig(
level=logging.INFO,
format='%(asctim... | 126 | 3,528 |
TradingAgents-CN | scripts/check_gemini_config.py | .py | """
检查脚本:查看 gemini-2.5-flash 在数据库中的完整配置
"""
import sys
from pathlib import Path
import asyncio
# 添加项目根目录到路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
async def check_gemini_config():
"""检查 gemini-2.5-flash 配置"""
print("=" * 80)
print("检查:gemini-2.5-flash 数据库配... | 100 | 3,005 |
TradingAgents-CN | scripts/debug_mongodb_time.py | .py | """
调试脚本:检查 MongoDB 中存储的时间格式
直接使用 pymongo 同步客户端,避免异步初始化问题
"""
import sys
import os
from pymongo import MongoClient
from datetime import datetime, timezone, timedelta
# 添加项目根目录到 Python 路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
def check_mongodb_time():
"""检查 MongoDB 中的时间存储格... | 105 | 3,985 |
TradingAgents-CN | scripts/test_mongodb_model_config.py | .py | """
测试脚本:验证从 MongoDB 读取模型配置
这个脚本会:
1. 测试从 MongoDB 读取模型配置
2. 验证字符串到枚举的转换
3. 测试模型验证逻辑
"""
import sys
from pathlib import Path
import asyncio
# 添加项目根目录到路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
async def test_mongodb_config():
"""测试 MongoDB 配置"""
print("=" * 80)... | 167 | 5,630 |
TradingAgents-CN | scripts/test_financial_data_fix.py | .py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""测试修复后的财务数据获取"""
from tradingagents.dataflows.optimized_china_data import OptimizedChinaDataProvider
# 创建数据流实例
df = OptimizedChinaDataProvider()
# 测试获取 000002 的财务数据
print("🔍 测试获取 000002 的财务数据...")
result = df._get_cached_raw_financial_data('000002')
if result:
pr... | 29 | 981 |
TradingAgents-CN | scripts/download_finnhub_data.py | .py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Finnhub数据下载脚本
这个脚本用于从Finnhub API下载新闻数据、内部人情绪数据和内部人交易数据。
支持批量下载和增量更新。
使用方法:
python scripts/download_finnhub_data.py --data-type news --symbols AAPL,TSLA,MSFT
python scripts/download_finnhub_data.py --all
python scripts/download_finnhub_data.py --force-refr... | 345 | 13,133 |
TradingAgents-CN | scripts/fix_full_symbol_index.py | .py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
修复 stock_basic_info 集合的 full_symbol 唯一索引问题
问题:
- MongoDB 的 stock_basic_info 集合有一个 full_symbol 字段的唯一索引
- 多条记录的 full_symbol 字段都是 null
- MongoDB 唯一索引不允许多个 null 值
- 导致数据同步时出现 E11000 duplicate key error
解决方案:
1. 删除 full_symbol 的唯一索引
2. 为所有记录生成 full_symbol 字段
3. 重新创建 full_s... | 214 | 7,296 |
TradingAgents-CN | scripts/test_fundamentals_with_stock_name.py | .py | #!/usr/bin/env python3
"""
测试基本面分析是否能正确获取股票名称
验证修复后的股票信息获取功能
"""
import sys
import os
# 添加项目根目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
def test_fundamentals_stock_name():
"""测试基本面分析中的股票名称获取"""
print("🔍 测试基本面分析中的股票名称获取")
print("=" * 50)
# 测试股票代码
... | 200 | 7,555 |
TradingAgents-CN | scripts/check_api_config.py | .py | #!/usr/bin/env python3
"""
API配置检查工具
检查各种API密钥的配置状态和可用性
"""
import os
import sys
from pathlib import Path
from dotenv import load_dotenv
# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
def check_env_file():
"""检查.env文件是否存在"""
env_file = project_root / ".en... | 197 | 6,313 |
TradingAgents-CN | scripts/check_tushare_data_range.py | .py | """
检查Tushare数据的实际时间范围
"""
import asyncio
from tradingagents.dataflows.providers.tushare_provider import TushareProvider
async def check_data_range():
"""检查Tushare数据范围"""
provider = TushareProvider()
# 测试几只老股票
test_symbols = [
('000001', '平安银行'), # 深圳最早的股票之一
('600000', '浦发银行... | 54 | 1,692 |
TradingAgents-CN | scripts/docker_deployment_init.py | .py | #!/usr/bin/env python3
"""
Docker 部署初始化脚本
用于新机器部署后的系统初始化,准备必要的基础数据
"""
import asyncio
import json
import os
import sys
import time
from datetime import datetime
from pathlib import Path
# 添加项目根目录到 Python 路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
from tradingagents.utils.log... | 407 | 14,057 |
TradingAgents-CN | scripts/test_concurrent_api.py | .py | """
测试并发API请求,验证数据源测试时其他接口是否会超时
"""
import asyncio
import aiohttp
import time
from datetime import datetime
async def test_notifications_api(session: aiohttp.ClientSession, test_id: int):
"""测试通知接口"""
url = "http://localhost:8000/api/notifications/unread_count"
headers = {
"Authorization": "Bearer... | 191 | 7,254 |
TradingAgents-CN | scripts/batch_update_docs.py | .py | #!/usr/bin/env python3
"""
批量更新文档脚本
为所有核心文档添加版本信息头部,修复常见问题
"""
import os
import re
import sys
from pathlib import Path
from typing import List, Dict
from datetime import datetime
# 添加项目根目录到路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
class DocumentationUpdater:
"""文档批量更新器"... | 252 | 8,793 |
TradingAgents-CN | scripts/test_selective_sync.py | .py | """
测试选择性数据同步功能
"""
import asyncio
import logging
from datetime import datetime
from tradingagents.config.database_manager import get_mongodb_client
from app.core.database import init_database
from app.worker.tushare_init_service import get_tushare_init_service
logging.basicConfig(level=logging.INFO)
logger = logging.... | 137 | 5,309 |
TradingAgents-CN | scripts/test_screening_view.py | .py | #!/usr/bin/env python3
"""
测试股票筛选视图
"""
import sys
import os
from pathlib import Path
# 添加项目根目录到 Python 路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
import asyncio
import logging
from app.core.database import init_database, get_mongo_db, close_database
from app.services.databa... | 115 | 3,672 |
TradingAgents-CN | scripts/test_financial_fallback.py | .py | """
测试财务数据降级逻辑
验证当 MongoDB 没有数据时,是否能正确降级到 AKShare
"""
import sys
from pathlib import Path
# 添加项目根目录到 Python 路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
# 设置日志级别为 INFO
import logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s | %(name)-20s | %(levelnam... | 139 | 5,495 |
TradingAgents-CN | scripts/test_qianfan_raw.py | .py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
千帆API原生测试脚本
直接使用千帆官方SDK测试连通性,不依赖项目集成代码
"""
import os
import sys
from dotenv import load_dotenv
# 加载环境变量
load_dotenv()
def test_qianfan_with_sdk():
"""使用千帆官方SDK测试"""
try:
import qianfan
# 优先使用新的API Key
api_key = os.getenv('QIAN... | 234 | 8,675 |
TradingAgents-CN | scripts/test_stock_data_preparation.py | .py | #!/usr/bin/env python3
"""
股票数据预获取功能测试脚本
验证新的股票数据准备机制是否正常工作
"""
import sys
import os
import time
from datetime import datetime, timedelta
# 添加项目根目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
def test_stock_data_preparation():
"""测试股票数据预获取功能"""
print("🧪 股票数据预获取功能... | 230 | 8,968 |
TradingAgents-CN | scripts/test_mongodb_storage_init.py | .py | #!/usr/bin/env python3
"""
测试 TradingAgents MongoDB 存储初始化
"""
import sys
from pathlib import Path
# 添加项目根目录到路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
# 初始化日志
from tradingagents.utils.logging_init import init_logging
init_logging()
from tradingagents.config.config_manager i... | 83 | 2,480 |
TradingAgents-CN | scripts/test_smart_progress.py | .py | #!/usr/bin/env python3
"""
测试智能进度跟踪器
"""
import sys
import os
import time
# 添加项目根目录到路径
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, project_root)
sys.path.insert(0, os.path.join(project_root, 'web'))
from web.utils.progress_tracker import SmartAnalysisProgressTracker
... | 123 | 4,284 |
TradingAgents-CN | scripts/test_google_sdk_basic.py | .py | """
简单测试脚本:验证 Google AI SDK 的基础功能
测试步骤:
1. 直接使用 google-generativeai SDK
2. 使用 langchain_google_genai.ChatGoogleGenerativeAI
3. 使用我们的 ChatGoogleOpenAI 适配器
"""
import sys
import os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
print("=" * 80)
print("🧪 Google AI SDK 基础功能测试")
print("... | 247 | 8,021 |
TradingAgents-CN | scripts/test_akshare_with_curl_cffi.py | .py | #!/usr/bin/env python3
"""
测试 AKShare 与 curl_cffi 集成
"""
import sys
sys.path.insert(0, '/app')
# 先 patch requests
import requests
import time
from curl_cffi import requests as curl_requests
original_get = requests.get
last_request_time = {'time': 0}
def patched_get(url, **kwargs):
"""Patch requests.get 使用 curl_c... | 73 | 2,095 |
TradingAgents-CN | scripts/analyze_amount_distribution.py | .py | #!/usr/bin/env python3
"""
分析成交额分布
"""
import sys
import os
from pathlib import Path
# 添加项目根目录到 Python 路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
import asyncio
import logging
from app.core.database import init_database, get_mongo_db, close_database
logging.basicConfig(leve... | 119 | 3,811 |
TradingAgents-CN | scripts/test_progress_tracking.py | .py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
测试进度跟踪系统
用于验证 LangGraph 节点名称映射和进度更新是否正确
"""
import sys
from pathlib import Path
# 添加项目根目录到 Python 路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
from tradingagents.utils.logging_init import get_logger
logger = get_logger("test"... | 271 | 8,192 |
TradingAgents-CN | scripts/migrate_user_preferences.py | .py | """
迁移用户偏好设置脚本
将旧的分析深度值("快速"、"标准"、"深度")迁移到新的值("1"、"2"、"3"、"4"、"5")
将旧的默认分析师值迁移到新的值
"""
import asyncio
import sys
from pathlib import Path
# 添加项目根目录到 Python 路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
from app.core.database import get_mongo_db_sync
from app.core.config import... | 121 | 4,439 |
TradingAgents-CN | scripts/test_akshare_docker.py | .py | #!/usr/bin/env python3
"""
测试 Docker 容器内 AKShare 新闻接口 - 检查请求头和反爬虫
"""
import akshare as ak
import json
import traceback
import requests
def test_with_different_headers():
"""测试不同请求头的效果"""
symbol = "000001"
print(f"=" * 80)
print(f"测试 AKShare 新闻接口 - 请求头对比")
print(f"=" * 80)
# 测试1:默认请求头
pri... | 107 | 3,544 |
TradingAgents-CN | scripts/demo_user_activity.py | .py | #!/usr/bin/env python3
"""
用户活动记录系统演示脚本
演示如何使用用户活动记录功能
"""
import sys
import time
from pathlib import Path
from datetime import datetime
# 添加项目路径
sys.path.append(str(Path(__file__).parent.parent))
try:
from web.utils.user_activity_logger import UserActivityLogger
print("✅ 成功导入用户活动记录器")
except ImportError as ... | 171 | 5,256 |
TradingAgents-CN | scripts/test_google_api_with_proxy.py | .py | """
测试 Google API 连接(使用代理)
"""
import sys
import os
from pathlib import Path
# 添加项目根目录到路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
# 加载 .env 文件
from dotenv import load_dotenv
load_dotenv()
print("=" * 80)
print("测试 Google API 连接(使用代理)")
print("=" * 80)
# 1. 配置代理
print("\n配置... | 144 | 4,380 |
TradingAgents-CN | scripts/test_news_sync.py | .py | #!/usr/bin/env python3
"""
测试新闻数据同步功能
"""
import asyncio
import sys
from pathlib import Path
# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
from app.core.database import init_database, get_mongo_db
from app.worker.tushare_sync_service import get_tushare_sync_servi... | 104 | 3,539 |
TradingAgents-CN | scripts/check_news_in_db.py | .py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""检查数据库中的新闻数据"""
from pymongo import MongoClient
from datetime import datetime, timedelta
# 连接数据库
client = MongoClient('mongodb://admin:tradingagents123@localhost:27017/?authSource=admin')
db = client['tradingagents']
print("=" * 80)
print("📰 检查数据库中的新闻数据")
print("=" * ... | 62 | 2,159 |
TradingAgents-CN | scripts/install_pdf_tools.py | .py | #!/usr/bin/env python3
"""
PDF工具安装脚本
自动安装PDF生成所需的工具
"""
import os
import sys
import subprocess
import platform
from pathlib import Path
# 导入日志模块
from tradingagents.utils.logging_manager import get_logger
logger = get_logger('scripts')
def check_tool(command, name):
"""检查工具是否已安装"""
try:
result = subpr... | 251 | 8,969 |
TradingAgents-CN | scripts/test_queue.py | .py | #!/usr/bin/env python3
"""
测试队列系统的脚本
"""
import asyncio
import sys
import json
from pathlib import Path
# 添加项目根目录到路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
from webapi.core.database import init_database, close_database
from webapi.core.redis_client import init_redis, close_... | 171 | 5,295 |
TradingAgents-CN | scripts/test_foreign_stock_priority.py | .py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
测试港股和美股数据源优先级配置
验证是否正确从数据库读取优先级
"""
import sys
import asyncio
from pathlib import Path
# 添加项目根目录到 Python 路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
async def test_priority():
"""测试数据源优先级读取"""
from app.core.database ... | 58 | 1,521 |
TradingAgents-CN | scripts/check_news_fields.py | .py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""检查数据库中新闻数据的字段"""
from pymongo import MongoClient
# 连接数据库
client = MongoClient('mongodb://admin:tradingagents123@localhost:27017/?authSource=admin')
db = client['tradingagents']
print("=" * 80)
print("📰 检查数据库中新闻数据的字段")
print("=" * 80)
# 查看一条新闻的完整字段
news = db.stock_ne... | 49 | 1,430 |
TradingAgents-CN | scripts/test_multi_period_sync.py | .py | #!/usr/bin/env python3
"""
测试多周期数据同步功能
"""
import asyncio
import sys
from pathlib import Path
# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
from tradingagents.dataflows.providers.tushare_provider import TushareProvider
from app.services.historical_data_service im... | 155 | 5,441 |
TradingAgents-CN | scripts/fix_logging_config_error.py | .py | #!/usr/bin/env python3
"""
修复日志配置KeyError错误
"""
import os
from pathlib import Path
def fix_logging_docker_config():
"""修复Docker日志配置文件"""
print("🔧 修复Docker日志配置文件...")
docker_config_content = '''# Docker环境专用日志配置 - 完整修复版
# 解决KeyError: 'file'错误
[logging]
level = "INFO"
[logging.format]
# 必须包含所有格式配置
co... | 282 | 8,070 |
TradingAgents-CN | scripts/fix_depth_value.py | .py | """
修复分析深度值
将分析深度从 "5" 改为 "4"(4级 - 深度分析)
"""
import sys
from pathlib import Path
# 添加项目根目录到 Python 路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
from app.core.database import get_mongo_db_sync
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(_... | 63 | 1,815 |
TradingAgents-CN | scripts/test_scheduler_management.py | .py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""测试定时任务管理功能"""
import requests
import json
from datetime import datetime
BASE_URL = "http://localhost:8000"
def get_auth_token():
"""获取认证token"""
try:
response = requests.post(
f"{BASE_URL}/api/auth/login",
json={"username": "adm... | 273 | 8,810 |
TradingAgents-CN | scripts/test_monkey_patch.py | .py | #!/usr/bin/env python3
"""
测试 monkey patch 是否在 Docker 环境中生效
"""
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import asyncio
import logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s | %(levelname)-8s | %(message)s'
)
logger = logging.g... | 80 | 2,738 |
TradingAgents-CN | scripts/补充行业信息_akshare.py | .py | #!/usr/bin/env python3
"""
使用 AKShare 补充 BaoStock 同步的股票的行业信息
功能:
1. 查询 stock_basic_info 集合中 industry="未知" 的股票
2. 使用 AKShare 的 stock_individual_info_em 接口获取行业信息
3. 更新数据库中的 industry 和 area 字段
使用方法:
python scripts/补充行业信息_akshare.py
python scripts/补充行业信息_akshare.py --limit 100 # 只处理前100只股票
python scripts/补充行... | 268 | 8,752 |
TradingAgents-CN | scripts/fix_duplicate_loggers.py | .py | #!/usr/bin/env python3
"""
修复重复logger定义问题的脚本
这个脚本会:
1. 扫描所有Python文件
2. 检测重复的logger = get_logger()定义
3. 移除重复定义,只保留文件头部的第一个定义
4. 生成详细的修复报告
"""
import os
import re
from pathlib import Path
from typing import List, Dict, Tuple
def find_python_files(root_dir: str, exclude_dirs: List[str] = None) -> List[str]:
"""查找所有... | 260 | 9,202 |
TradingAgents-CN | scripts/migrate_add_market_type.py | .py | #!/usr/bin/env python3
"""
数据迁移脚本:为已有的分析报告添加 market_type 字段
使用方法:
python scripts/migrate_add_market_type.py [--dry-run]
参数:
--dry-run: 只显示将要更新的数据,不实际执行更新
"""
import sys
import asyncio
from pathlib import Path
# 添加项目根目录到路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
fro... | 197 | 6,138 |
TradingAgents-CN | scripts/test_sina_columns.py | .py | #!/usr/bin/env python3
"""测试新浪接口返回的列名"""
import akshare as ak
print("🔍 测试新浪接口返回的列名...")
# 获取数据
df = ak.stock_zh_a_spot()
print(f"\n✅ 获取到 {len(df)} 条记录")
print(f"\n📋 列名: {list(df.columns)}")
# 显示前10条数据,查看代码格式
print(f"\n📊 前10条数据(查看代码格式):")
print(df[['代码', '名称', '最新价']].head(10))
# 查找测试股票(尝试不同的代码格式)
test_codes = ... | 60 | 1,993 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.