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 | app/services/data_sources/base.py | .py | """
Base classes and shared typing for data source adapters
"""
from abc import ABC, abstractmethod
from typing import Optional, Dict
import pandas as pd
class DataSourceAdapter(ABC):
"""数据源适配器基类"""
def __init__(self):
self._priority: Optional[int] = None # 动态优先级,从数据库加载
@property
@abstractm... | 70 | 2,440 |
TradingAgents-CN | app/services/database/cleanup.py | .py | """
Cleanup routines extracted from DatabaseService.
"""
from __future__ import annotations
from datetime import datetime, timedelta
from typing import Any, Dict
from app.core.database import get_mongo_db
async def cleanup_old_data(days: int) -> Dict[str, Any]:
db = get_mongo_db()
cutoff_date = datetime.utc... | 99 | 3,247 |
TradingAgents-CN | app/services/database/__init__.py | .py | from . import status_checks, backups, cleanup, serialization
__all__ = [
"status_checks",
"backups",
"cleanup",
"serialization",
]
| 10 | 149 |
TradingAgents-CN | app/services/database/status_checks.py | .py | """
Database status and connection checks, extracted from DatabaseService.
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Dict
from app.core.database import get_mongo_db, get_redis_client
from app.core.config import settings
async def get_mongodb_status() -> Dict[str, A... | 102 | 3,669 |
TradingAgents-CN | app/services/database/backups.py | .py | """
Backup, import, and export routines extracted from DatabaseService.
"""
from __future__ import annotations
import json
import os
import gzip
import asyncio
import subprocess
import shutil
from datetime import datetime
from typing import Any, Dict, List, Optional
import logging
from bson import ObjectId
from app.... | 538 | 19,200 |
TradingAgents-CN | app/services/database/serialization.py | .py | """
Serialization helpers for MongoDB documents.
"""
from __future__ import annotations
from datetime import datetime
from bson import ObjectId
def serialize_document(doc: dict) -> dict:
"""Serialize special MongoDB types to JSON-friendly primitives.
- ObjectId -> str
- datetime -> ISO string
- Recur... | 40 | 1,248 |
TradingAgents-CN | app/services/screening/eval_utils.py | .py | """
Utility functions for screening evaluation and DSL parsing.
Extracted from ScreeningService to separate concerns while keeping API unchanged.
"""
from __future__ import annotations
from typing import Any, Dict, List, Optional, Iterable
import pandas as pd
import numpy as np
def collect_fields_from_conditions(nod... | 168 | 5,366 |
TradingAgents-CN | app/services/enhanced_screening/utils.py | .py | """
Utility helpers for EnhancedScreeningService to separate analysis and conversion logic.
"""
from __future__ import annotations
from typing import Any, Dict, List, Optional
from app.models.screening import ScreeningCondition, FieldType, BASIC_FIELDS_INFO
def analyze_conditions(conditions: List[ScreeningCondition... | 77 | 2,734 |
TradingAgents-CN | app/services/progress/log_handler.py | .py | """
进度日志处理器
监控TradingAgents的日志输出,自动更新进度跟踪器
"""
import logging
import re
import threading
from typing import Dict, Optional
from .tracker import RedisProgressTracker
logger = logging.getLogger("app.services.progress_log_handler")
class ProgressLogHandler(logging.Handler):
"""进度日志处理器,监控TradingAgents日志并更新进度"""
... | 186 | 7,282 |
TradingAgents-CN | app/services/progress/__init__.py | .py | """
Progress 子包(过渡期):对进度跟踪与日志处理进行结构化组织。
当前阶段采用“新路径重导出到旧实现”的方式,保持 API 稳定。
"""
from .tracker import RedisProgressTracker, get_progress_by_id
from .log_handler import (
ProgressLogHandler,
get_progress_log_handler,
register_analysis_tracker,
unregister_analysis_tracker,
)
| 13 | 393 |
TradingAgents-CN | app/services/progress/tracker.py | .py | """
进度跟踪器(过渡期)
- 暂时从旧模块导入 RedisProgressTracker 类
- 在本模块内提供 get_progress_by_id 的实现(与旧实现一致,修正 cls 引用)
"""
from typing import Any, Dict, Optional, List
import json
import os
import logging
import time
logger = logging.getLogger("app.services.progress.tracker")
from dataclasses import dataclass, asdict
from datetime im... | 544 | 23,718 |
TradingAgents-CN | app/core/rate_limiter.py | .py | """
速率限制器
用于控制API调用频率,避免超过数据源的限流限制
"""
import asyncio
import time
import logging
from collections import deque
from typing import Optional
logger = logging.getLogger(__name__)
class RateLimiter:
"""
滑动窗口速率限制器
使用滑动窗口算法精确控制API调用频率
"""
def __init__(self, max_calls: int, time_window: float,... | 229 | 7,581 |
TradingAgents-CN | app/core/__init__.py | .py | """
Core module for TradingAgents FastAPI backend
""" | 3 | 53 |
TradingAgents-CN | app/core/config_bridge.py | .py | """
配置桥接模块
将统一配置系统的配置桥接到环境变量,供 TradingAgents 核心库使用
"""
import os
import json
import logging
from pathlib import Path
from typing import Optional
logger = logging.getLogger("app.config_bridge")
def bridge_config_to_env():
"""
将统一配置桥接到环境变量
这个函数会:
1. 从数据库读取大模型厂家配置(API 密钥、超时、温度等)
2. 将配置写入环境变量
3... | 748 | 31,373 |
TradingAgents-CN | app/core/dev_config.py | .py | """
开发环境配置
优化开发体验,减少不必要的文件监控
"""
import logging
from typing import List, Optional
class DevConfig:
"""开发环境配置类"""
# 文件监控配置
RELOAD_DIRS: List[str] = ["app"]
# 排除的文件和目录
RELOAD_EXCLUDES: List[str] = [
# Python缓存文件
"__pycache__",
"*.pyc",
"*.pyo",
"*.... | 144 | 3,701 |
TradingAgents-CN | app/core/database.py | .py | """
数据库连接管理模块
增强版本,支持连接池、健康检查和错误恢复
"""
import logging
import asyncio
from typing import Optional
from motor.motor_asyncio import AsyncIOMotorClient, AsyncIOMotorDatabase
from pymongo import MongoClient
from pymongo.database import Database
from redis.asyncio import Redis, ConnectionPool
from pymongo.errors import Serv... | 443 | 15,177 |
TradingAgents-CN | app/core/logging_config.py | .py | import logging
import logging.config
import sys
from pathlib import Path
import os
import platform
from app.core.logging_context import LoggingContextFilter, trace_id_var
# 🔥 在 Windows 上使用 concurrent-log-handler 避免文件占用问题
_IS_WINDOWS = platform.system() == "Windows"
if _IS_WINDOWS:
try:
from concurrent_lo... | 424 | 18,400 |
TradingAgents-CN | app/core/logging_context.py | .py | import logging
import contextvars
# Shared contextvar for trace id across the whole process
trace_id_var: contextvars.ContextVar[str] = contextvars.ContextVar("trace_id", default="-")
class LoggingContextFilter(logging.Filter):
"""Injects trace_id from contextvars into LogRecord.
Always sets record.trace_id ... | 20 | 579 |
TradingAgents-CN | app/core/unified_config.py | .py | """
统一配置管理系统
整合 config/、tradingagents/config/ 和 webapi 的配置管理
"""
import json
import os
from pathlib import Path
from typing import Dict, List, Optional, Any, Union
from datetime import datetime
import asyncio
from dataclasses import dataclass, asdict
from app.models.config import (
LLMConfig, DataSourceConfig, Da... | 503 | 20,779 |
TradingAgents-CN | app/core/redis_client.py | .py | """
Redis客户端配置和连接管理
"""
import redis.asyncio as redis
import logging
from typing import Optional
from .config import settings
logger = logging.getLogger(__name__)
# 全局Redis连接池
redis_pool: Optional[redis.ConnectionPool] = None
redis_client: Optional[redis.Redis] = None
async def init_redis():
"""初始化Redis连接"""
... | 203 | 6,250 |
TradingAgents-CN | app/core/startup_validator.py | .py | """
启动配置验证器
验证系统启动所需的必需配置项,提供友好的错误提示。
"""
import os
import logging
from typing import List, Dict, Any, Optional
from dataclasses import dataclass
from enum import Enum
from app.core.config import settings
logger = logging.getLogger(__name__)
class ConfigLevel(Enum):
"""配置级别"""
REQUIRED = "required" #... | 355 | 12,509 |
TradingAgents-CN | app/core/config.py | .py | from pydantic import Field
from pydantic_settings import BaseSettings, SettingsConfigDict
from typing import List
import os
import warnings
import re
import getpass
from pathlib import Path
# Legacy env var aliases (deprecated): map API_HOST/PORT/DEBUG -> HOST/PORT/DEBUG
_LEGACY_ENV_ALIASES = {
"API_HOST": "HOST",... | 383 | 17,565 |
TradingAgents-CN | app/core/config_compat.py | .py | """
配置系统兼容层
为旧的 tradingagents 库提供配置兼容接口,
使其能够使用新的配置系统而无需修改代码。
⚠️ 此模块仅用于向后兼容,新代码应直接使用 ConfigService
"""
import os
import asyncio
from typing import Dict, Any, Optional, List
from functools import lru_cache
import warnings
from app.core.config import settings
class ConfigManagerCompat:
"""
ConfigManager 兼容类... | 267 | 7,831 |
TradingAgents-CN | app/core/response.py | .py | """
统一API响应格式工具
"""
from datetime import datetime
from typing import Any, Optional, Dict
from app.utils.timezone import now_tz
def ok(data: Any = None, message: str = "ok") -> Dict[str, Any]:
"""标准成功响应
返回结构:{"success": True, "data": data, "message": message, "timestamp": ...}
"""
return {
"suc... | 31 | 834 |
TradingAgents-CN | app/scripts/migrate_mongo_db.py | .py | import argparse
import json
import os
from datetime import datetime
from pathlib import Path
from typing import Dict, Iterable, List, Optional, Set
from pymongo import MongoClient
from app.core.config import settings
DEFAULT_EXCLUDED_COLLECTIONS = {
"analysis_tasks",
"analysis_reports",
"historical_data"... | 222 | 7,124 |
TradingAgents-CN | app/scripts/normalize_provider_keys.py | .py | import argparse
from datetime import datetime
from typing import Any, Dict, Iterable, List, Optional, Sequence
from pymongo import MongoClient
from app.core.config import settings
from tradingagents.llm_clients.provider_keys import canonical_aliases, normalize_provider_key
def _now() -> str:
return datetime.utc... | 218 | 8,327 |
TradingAgents-CN | app/scripts/init_providers.py | .py | #!/usr/bin/env python3
"""
初始化大模型厂家数据脚本
"""
import asyncio
import sys
import os
from datetime import datetime
# 添加项目根目录到Python路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))
from app.core.database import init_db, get_mongo_db
from app.models.config import LLMProvider
from tradingagents.llm... | 172 | 8,890 |
TradingAgents-CN | app/utils/timezone.py | .py | from __future__ import annotations
from datetime import datetime
from zoneinfo import ZoneInfo
from typing import Optional
from app.core.config import settings
def get_tz_name() -> str:
"""Return configured timezone name, preferring DB system_settings.app_timezone if cached.
Fallback order: DB (cached) > en... | 58 | 1,830 |
TradingAgents-CN | app/utils/api_key_utils.py | .py | """
API Key 处理工具函数
提供统一的 API Key 验证、缩略、环境变量读取等功能
"""
import os
from typing import Optional
def is_valid_api_key(api_key: Optional[str]) -> bool:
"""
判断 API Key 是否有效
有效的 API Key 必须满足:
1. 不能为空
2. 长度必须 > 10
3. 不能是占位符(前缀:your_, your-)
4. 不能是占位符(后缀:_here, -here)
5. 不能是截断的密钥(包含 '...')... | 166 | 4,111 |
TradingAgents-CN | app/utils/report_exporter.py | .py | """
报告导出工具 - 支持 Markdown、Word、PDF 格式
依赖安装:
pip install pypandoc markdown
PDF 导出需要额外工具:
- wkhtmltopdf (推荐): https://wkhtmltopdf.org/downloads.html
- 或 LaTeX: https://www.latex-project.org/get/
"""
import logging
import os
import tempfile
from pathlib import Path
from typing import Dict, Any, Optional
log... | 669 | 20,653 |
TradingAgents-CN | app/utils/error_formatter.py | .py | """
错误信息格式化工具
将技术性错误转换为用户友好的错误提示,明确指出问题所在(数据源、大模型、配置等)
"""
import re
from typing import Dict, Optional, Tuple
from enum import Enum
class ErrorCategory(str, Enum):
"""错误类别"""
LLM_API_KEY = "llm_api_key" # 大模型 API Key 错误
LLM_NETWORK = "llm_network" # 大模型网络错误
LLM_QUOTA = "llm_quota" # 大模型配额/限流错误
... | 414 | 17,939 |
TradingAgents-CN | app/utils/trading_time.py | .py | """
交易时间判断工具模块
提供统一的交易时间判断逻辑,用于判断当前是否在A股交易时间内。
"""
from datetime import datetime, time as dtime
from typing import Optional
from zoneinfo import ZoneInfo
from app.core.config import settings
def is_trading_time(now: Optional[datetime] = None) -> bool:
"""
判断是否在A股交易时间或收盘后缓冲期
交易时间:
- 上午:9:30-11:30
... | 180 | 4,599 |
TradingAgents-CN | app/constants/model_capabilities.py | .py | """
模型能力分级系统
定义模型的能力等级、适用角色、特性标签等元数据,
用于智能匹配分析深度和模型选择。
🆕 聚合渠道支持:
- 支持 302.AI、OpenRouter、One API 等聚合渠道
- 聚合渠道的模型名称格式:{provider}/{model}(如 openai/gpt-4)
- 系统会自动映射到原厂模型的能力配置
"""
from enum import IntEnum, Enum
from typing import Dict, List, Any, Tuple
class ModelCapabilityLevel(IntEnum):
"""模型能力等级(1-5级)"""
BA... | 488 | 22,833 |
TradingAgents-CN | app/middleware/__init__.py | .py | """
中间件模块
"""
| 4 | 24 |
TradingAgents-CN | app/middleware/request_id.py | .py | """
请求ID/Trace-ID 中间件
- 为每个请求生成唯一 ID(trace_id),写入 request.state 与响应头
- 将 trace_id 写入 logging 的 contextvars,使所有日志自动带出
"""
from fastapi import Request, Response
from starlette.middleware.base import BaseHTTPMiddleware
import uuid
import time
import logging
from typing import Callable
from app.core.logging_context impor... | 76 | 2,378 |
TradingAgents-CN | app/middleware/rate_limit.py | .py | """
速率限制中间件
防止API滥用,实现用户级和端点级速率限制
"""
from fastapi import Request, Response, HTTPException
from starlette.middleware.base import BaseHTTPMiddleware
import logging
from typing import Callable, Dict, Optional
from core.redis_client import get_redis_service, RedisKeys
logger = logging.getLogger(__name__)
class RateLim... | 177 | 6,174 |
TradingAgents-CN | app/middleware/error_handler.py | .py | """
错误处理中间件
"""
from fastapi import Request, Response
from fastapi.responses import JSONResponse
from starlette.middleware.base import BaseHTTPMiddleware
import logging
import traceback
from typing import Callable
logger = logging.getLogger(__name__)
class ErrorHandlerMiddleware(BaseHTTPMiddleware):
"""全局错误处理中间... | 89 | 2,763 |
TradingAgents-CN | app/middleware/operation_log_middleware.py | .py | """
操作日志记录中间件
自动记录用户的API操作日志
"""
import time
import json
import logging
from typing import Optional, Dict, Any
from fastapi import Request, Response
from starlette.middleware.base import BaseHTTPMiddleware
from app.services.operation_log_service import log_operation
from app.models.operation_log import ActionType
lo... | 313 | 10,159 |
TradingAgents-CN | app/models/user.py | .py | """
用户数据模型
"""
from datetime import datetime, timezone
from app.utils.timezone import now_tz
from typing import Optional, Dict, Any, Annotated, List
from pydantic import BaseModel, Field, BeforeValidator, PlainSerializer, ConfigDict, field_serializer
from pydantic.json_schema import JsonSchemaValue
from pydantic_core ... | 172 | 5,268 |
TradingAgents-CN | app/models/analysis.py | .py | """
分析相关数据模型
"""
from datetime import datetime
from typing import Optional, List, Dict, Any
from pydantic import BaseModel, Field, ConfigDict, field_serializer
from enum import Enum
from bson import ObjectId
from .user import PyObjectId
from app.utils.timezone import now_tz
class AnalysisStatus(str, Enum):
"""分析... | 237 | 7,899 |
TradingAgents-CN | app/models/__init__.py | .py | """
数据模型模块
"""
# 导入股票数据模型
from .stock_models import (
StockBasicInfoExtended,
MarketQuotesExtended,
MarketInfo,
TechnicalIndicators,
StockBasicInfoResponse,
MarketQuotesResponse,
StockListResponse,
MarketType,
ExchangeType,
CurrencyType,
StockStatus
)
__all__ = [
"Stock... | 33 | 602 |
TradingAgents-CN | app/models/screening.py | .py | """
股票筛选相关的数据模型
"""
from pydantic import BaseModel, Field
from typing import Any, Dict, List, Optional, Union
from enum import Enum
class OperatorType(str, Enum):
"""筛选操作符类型"""
GT = ">" # 大于
LT = "<" # 小于
GTE = ">=" # 大于等于
LTE = "<=" # 小于等于
EQ = "==" ... | 347 | 13,381 |
TradingAgents-CN | app/models/stock_models.py | .py | """
股票数据模型 - 基于现有集合扩展
采用方案B: 在现有集合基础上扩展字段,保持向后兼容
"""
from datetime import datetime, date
from typing import Optional, Dict, Any, List, Literal
from pydantic import BaseModel, Field
from bson import ObjectId
def to_str_id(v: Any) -> str:
"""ObjectId转字符串工具函数"""
try:
if isinstance(v, ObjectId):
... | 246 | 9,643 |
TradingAgents-CN | app/models/operation_log.py | .py | """
操作日志数据模型
"""
from datetime import datetime
from typing import Dict, Any, Optional, List
from pydantic import BaseModel, Field, field_serializer
from bson import ObjectId
class OperationLogCreate(BaseModel):
"""创建操作日志请求"""
action_type: str = Field(..., description="操作类型")
action: str = Field(..., desc... | 138 | 5,791 |
TradingAgents-CN | app/models/notification.py | .py | """
通知数据模型(MongoDB + Pydantic)
"""
from datetime import datetime
from typing import Optional, Literal, List, Dict, Any
from pydantic import BaseModel, Field, field_serializer
from bson import ObjectId
from app.utils.timezone import now_tz
# 简单工具:ObjectId -> str
def to_str_id(v: Any) -> str:
try:
if isinst... | 75 | 1,974 |
TradingAgents-CN | app/models/config.py | .py | """
系统配置相关数据模型
"""
from datetime import datetime, timezone
from app.utils.timezone import now_tz
from typing import Optional, Dict, Any, List
from pydantic import BaseModel, Field, ConfigDict, field_serializer
from enum import Enum
from bson import ObjectId
from .user import PyObjectId
class ModelProvider(str, Enum)... | 498 | 21,487 |
TradingAgents-CN | app/worker/tushare_init_service.py | .py | """
Tushare数据初始化服务
用于首次部署时的完整数据初始化,包括基础数据、历史数据、财务数据等
"""
import asyncio
import logging
from datetime import datetime, timedelta
from typing import Dict, Any, Optional, List
from dataclasses import dataclass
from app.core.database import get_mongo_db
from app.worker.tushare_sync_service import get_tushare_sync_service
... | 460 | 18,424 |
TradingAgents-CN | app/worker/baostock_sync_service.py | .py | #!/usr/bin/env python3
"""
BaoStock数据同步服务
提供BaoStock数据的批量同步功能,集成到APScheduler调度系统
"""
import asyncio
import logging
from datetime import datetime, timedelta
from typing import Dict, Any, List, Optional
from dataclasses import dataclass
from app.core.config import get_settings
from app.core.database import get_database
... | 608 | 24,387 |
TradingAgents-CN | app/worker/akshare_sync_service.py | .py | """
AKShare数据同步服务
基于AKShare提供器的统一数据同步方案
"""
import asyncio
import logging
from datetime import datetime, timedelta
from typing import Dict, Any, List, Optional
from app.core.database import get_mongo_db
from app.services.historical_data_service import get_historical_data_service
from app.services.news_data_service imp... | 1,236 | 49,951 |
TradingAgents-CN | app/worker/akshare_init_service.py | .py | """
AKShare数据初始化服务
用于首次部署时的完整数据初始化,包括基础数据、历史数据、财务数据等
"""
import asyncio
import logging
from datetime import datetime, timedelta
from typing import Dict, Any, Optional, List
from dataclasses import dataclass
from app.core.database import get_mongo_db
from app.worker.akshare_sync_service import get_akshare_sync_service
... | 463 | 18,562 |
TradingAgents-CN | app/worker/us_data_service.py | .py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
美股数据服务(按需获取+缓存模式)
功能:
1. 按需从数据源获取美股信息(yfinance/finnhub)
2. 自动缓存到 MongoDB,避免重复请求
3. 支持多数据源:同一股票可有多个数据源记录
4. 使用 (code, source) 联合查询进行 upsert 操作
设计说明:
- 采用按需获取+缓存模式,避免批量同步触发速率限制
- 参考A股数据源管理方式(Tushare/AKShare/BaoStock)
- 缓存时长可配置(默认24小时)
"""
import logging
from datetime ... | 193 | 6,707 |
TradingAgents-CN | app/worker/multi_period_sync_service.py | .py | #!/usr/bin/env python3
"""
多周期历史数据同步服务
支持日线、周线、月线数据的统一同步
"""
import asyncio
import logging
from datetime import datetime, timedelta
from typing import Dict, Any, List, Optional
from dataclasses import dataclass
from app.services.historical_data_service import get_historical_data_service
from app.worker.tushare_sync_se... | 375 | 13,454 |
TradingAgents-CN | app/worker/analysis_worker.py | .py | """
分析任务Worker进程
消费队列中的分析任务,调用TradingAgents进行股票分析
"""
import asyncio
import logging
import signal
import sys
import uuid
import traceback
from datetime import datetime
from pathlib import Path
from typing import Optional, Dict, Any
# 添加项目根目录到路径
project_root = Path(__file__).parent.parent.parent
sys.path.insert(0, str... | 275 | 9,764 |
TradingAgents-CN | app/worker/__init__.py | .py | """Worker package for analysis and related background jobs."""
| 3 | 64 |
TradingAgents-CN | app/worker/baostock_init_service.py | .py | #!/usr/bin/env python3
"""
BaoStock数据初始化服务
提供BaoStock数据的完整初始化功能
"""
import asyncio
import logging
from datetime import datetime, timedelta
from typing import Dict, Any, List, Optional
from dataclasses import dataclass, field
from app.core.config import get_settings
from app.core.database import get_database
from app.w... | 365 | 15,107 |
TradingAgents-CN | app/worker/example_sdk_sync_service.py | .py | """
示例SDK数据同步服务 (app层)
展示如何创建数据同步服务,将外部SDK数据写入标准化的MongoDB集合
架构说明:
- tradingagents层: 纯数据获取和标准化,不涉及数据库操作
- app层: 数据同步服务,负责数据库操作和业务逻辑
- 数据流: 外部SDK → tradingagents适配器 → app同步服务 → MongoDB
"""
import asyncio
import logging
from datetime import datetime, timedelta
from typing import List, Dict, Any, Optional
import os
from ... | 355 | 13,285 |
TradingAgents-CN | app/worker/financial_data_sync_service.py | .py | #!/usr/bin/env python3
"""
财务数据同步服务
统一管理三数据源的财务数据同步
"""
import asyncio
import logging
from datetime import datetime, timezone
from typing import Dict, Any, List, Optional
from dataclasses import dataclass, field
from app.core.database import get_mongo_db
from app.services.financial_data_service import get_financial_da... | 336 | 11,984 |
TradingAgents-CN | app/worker/tushare_sync_service.py | .py | """
Tushare数据同步服务
负责将Tushare数据同步到MongoDB标准化集合
"""
import asyncio
from datetime import datetime, timedelta, timezone
from typing import List, Dict, Any, Optional
import logging
from tradingagents.dataflows.providers.china.tushare import TushareProvider
from app.services.stock_data_service import get_stock_data_service
... | 1,360 | 56,523 |
TradingAgents-CN | app/worker/hk_sync_service.py | .py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
港股数据服务(按需获取+缓存模式)
功能:
1. 按需从数据源获取港股信息(yfinance/akshare)
2. 自动缓存到 MongoDB,避免重复请求
3. 支持多数据源:同一股票可有多个数据源记录
4. 使用 (code, source) 联合查询进行 upsert 操作
设计说明:
- 采用按需获取+缓存模式,避免批量同步触发速率限制
- 参考A股数据源管理方式(Tushare/AKShare/BaoStock)
- 缓存时长可配置(默认24小时)
"""
import asyncio
import logging... | 533 | 19,675 |
TradingAgents-CN | app/worker/news_data_sync_service.py | .py | """
新闻数据同步服务
支持多数据源新闻数据同步和情绪分析
"""
import asyncio
import logging
from typing import List, Dict, Any, Optional
from datetime import datetime, timedelta
from dataclasses import dataclass, field
from app.services.news_data_service import get_news_data_service
from tradingagents.dataflows.providers.china.tushare import ge... | 519 | 20,264 |
TradingAgents-CN | app/worker/hk_data_service.py | .py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
港股数据服务(按需获取+缓存模式)
功能:
1. 按需从数据源获取港股信息(yfinance/akshare)
2. 自动缓存到 MongoDB,避免重复请求
3. 支持多数据源:同一股票可有多个数据源记录
4. 使用 (code, source) 联合查询进行 upsert 操作
设计说明:
- 采用按需获取+缓存模式,避免批量同步触发速率限制
- 参考A股数据源管理方式(Tushare/AKShare/BaoStock)
- 缓存时长可配置(默认24小时)
"""
import logging
from datetime ... | 194 | 6,753 |
TradingAgents-CN | app/worker/us_sync_service.py | .py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
美股数据同步服务(支持多数据源)
功能:
1. 从 yfinance 同步美股基础信息和行情
2. 支持多数据源存储:同一股票可有多个数据源记录
3. 使用 (code, source) 联合查询进行 upsert 操作
设计说明:
- 参考A股多数据源同步服务设计(Tushare/AKShare/BaoStock)
- 主要使用 yfinance 作为数据源
- 批量更新操作提高性能
"""
import asyncio
import logging
from datetime import datetime
from ty... | 444 | 15,848 |
storm | setup.py | .py | import re
from setuptools import setup, find_packages
# Read the content of the README file
with open("README.md", encoding="utf-8") as f:
long_description = f.read()
# Remove p tags.
pattern = re.compile(r"<p.*?>.*?</p>", re.DOTALL)
long_description = re.sub(pattern, "", long_description)
# Read the... | 39 | 1,267 |
storm | knowledge_storm/lm.py | .py | import backoff
import dspy
import functools
import logging
import os
import random
import requests
import threading
from typing import Optional, Literal, Any
import ujson
from pathlib import Path
from dsp import ERRORS, backoff_hdlr, giveup_hdlr
from dsp.modules.hf import openai_to_hf
from dsp.modules.hf_client impor... | 1,287 | 42,725 |
storm | knowledge_storm/utils.py | .py | import concurrent.futures
import dspy
import httpx
import json
import logging
import os
import pickle
import re
import regex
import sys
import toml
from typing import List, Dict
from tqdm import tqdm
from langchain_text_splitters import RecursiveCharacterTextSplitter
from trafilatura import extract
from .lm import Li... | 794 | 31,781 |
storm | knowledge_storm/dataclass.py | .py | import dspy
import numpy as np
import re
import threading
from typing import Set, Dict, List, Optional, Union, Tuple
from .encoder import Encoder
from .interface import Information
class ConversationTurn:
"""
A class to represent a turn in a conversation.
Attributes:
role (str): A short phrase o... | 850 | 32,574 |
storm | knowledge_storm/encoder.py | .py | import os
import numpy as np
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import List, Tuple, Union, Optional, Dict, Literal
from pathlib import Path
try:
import warnings
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=UserWarning)
if ... | 179 | 6,812 |
storm | knowledge_storm/logging_wrapper.py | .py | from contextlib import contextmanager
import time
import pytz
from datetime import datetime
# Define California timezone
CALIFORNIA_TZ = pytz.timezone("America/Los_Angeles")
class EventLog:
def __init__(self, event_name):
self.event_name = event_name
self.start_time = None
self.end_time =... | 213 | 7,707 |
storm | knowledge_storm/rm.py | .py | import logging
import os
from typing import Callable, Union, List
import backoff
import dspy
import requests
from dsp import backoff_hdlr, giveup_hdlr
from .utils import WebPageHelper
class YouRM(dspy.Retrieve):
def __init__(self, ydc_api_key=None, k=3, is_valid_source: Callable = None):
super().__init_... | 1,239 | 47,638 |
storm | knowledge_storm/interface.py | .py | import concurrent.futures
import dspy
import functools
import hashlib
import json
import logging
import time
from abc import ABC, abstractmethod
from collections import OrderedDict
from typing import Dict, List, Optional, Union, TYPE_CHECKING
from .utils import ArticleTextProcessing
logging.basicConfig(
level=log... | 609 | 21,021 |
storm | knowledge_storm/storm_wiki/engine.py | .py | import json
import logging
import os
from dataclasses import dataclass, field
from typing import Union, Literal, Optional
import dspy
from .modules.article_generation import StormArticleGenerationModule
from .modules.article_polish import StormArticlePolishingModule
from .modules.callback import BaseCallbackHandler
f... | 442 | 17,988 |
storm | knowledge_storm/storm_wiki/modules/callback.py | .py | class BaseCallbackHandler:
"""Base callback handler that can be used to handle callbacks from the STORM pipeline."""
def on_identify_perspective_start(self, **kwargs):
"""Run when the perspective identification starts."""
pass
def on_identify_perspective_end(self, perspectives: list[str], ... | 35 | 1,219 |
storm | knowledge_storm/storm_wiki/modules/persona_generator.py | .py | import logging
import re
from typing import Union, List
import dspy
import requests
from bs4 import BeautifulSoup
def get_wiki_page_title_and_toc(url):
"""Get the main title and table of contents from an url of a Wikipedia page."""
response = requests.get(url)
soup = BeautifulSoup(response.content, "htm... | 155 | 6,621 |
storm | knowledge_storm/storm_wiki/modules/article_polish.py | .py | import copy
from typing import Union
import dspy
from .storm_dataclass import StormArticle
from ...interface import ArticlePolishingModule
from ...utils import ArticleTextProcessing
class StormArticlePolishingModule(ArticlePolishingModule):
"""
The interface for article generation stage. Given topic, collec... | 103 | 4,752 |
storm | knowledge_storm/storm_wiki/modules/knowledge_curation.py | .py | import concurrent.futures
import logging
import os
from concurrent.futures import as_completed
from typing import Union, List, Tuple, Optional, Dict
import dspy
from .callback import BaseCallbackHandler
from .persona_generator import StormPersonaGenerator
from .storm_dataclass import DialogueTurn, StormInformationTab... | 394 | 16,320 |
storm | knowledge_storm/storm_wiki/modules/retriever.py | .py | from typing import Union, List
from urllib.parse import urlparse
import dspy
from ...interface import Retriever, Information
from ...utils import ArticleTextProcessing
# Internet source restrictions according to Wikipedia standard:
# https://en.wikipedia.org/wiki/Wikipedia:Reliable_sources/Perennial_sources
GENERALL... | 234 | 4,973 |
storm | knowledge_storm/storm_wiki/modules/storm_dataclass.py | .py | import copy
import re
from collections import OrderedDict
from typing import Union, Optional, Any, List, Tuple, Dict
import numpy as np
from sentence_transformers import SentenceTransformer
from sklearn.metrics.pairwise import cosine_similarity
from ...interface import Information, InformationTable, Article, ArticleS... | 505 | 19,508 |
storm | knowledge_storm/storm_wiki/modules/article_generation.py | .py | import concurrent.futures
import copy
import logging
from concurrent.futures import as_completed
from typing import List, Union
import dspy
from .callback import BaseCallbackHandler
from .storm_dataclass import StormInformationTable, StormArticle
from ...interface import ArticleGenerationModule, Information
from ...u... | 177 | 7,385 |
storm | knowledge_storm/storm_wiki/modules/outline_generation.py | .py | from typing import Union, Optional, Tuple
import dspy
from .callback import BaseCallbackHandler
from .storm_dataclass import StormInformationTable, StormArticle
from ...interface import OutlineGenerationModule
from ...utils import ArticleTextProcessing
class StormOutlineGenerationModule(OutlineGenerationModule):
... | 168 | 7,352 |
storm | knowledge_storm/collaborative_storm/engine.py | .py | import dspy
import os
from dataclasses import dataclass, field, asdict
from typing import List, Union, Literal, Optional, Dict
from .modules import collaborative_storm_utils as collaborative_storm_utils
from .modules.callback import BaseCallbackHandler
from .modules.co_storm_agents import (
SimulatedUser,
Pure... | 762 | 32,330 |
storm | knowledge_storm/collaborative_storm/modules/callback.py | .py | from typing import List
from ...interface import Information
class BaseCallbackHandler:
"""Base callback handler to manage callbacks from the Co-STORM pipeline."""
def on_turn_policy_planning_start(self, **kwargs):
"""Run when the turn policy planning begins, before deciding the direction or goal for... | 111 | 5,274 |
storm | knowledge_storm/collaborative_storm/modules/costorm_expert_utterance_generator.py | .py | import dspy
from typing import Union
from .callback import BaseCallbackHandler
from .collaborative_storm_utils import (
trim_output_after_hint,
extract_and_remove_citations,
keep_first_and_last_paragraph,
)
from .grounded_question_answering import AnswerQuestionModule
from .grounded_question_generation im... | 161 | 7,095 |
storm | knowledge_storm/collaborative_storm/modules/warmstart_hierarchical_chat.py | .py | """
Warm starts the Co-STORM system by conducting a background information search to establish a shared conceptual space with the user.
This stage functions as a mini-STORM, where multiple LLM agents are spawned with different perspectives to engage in multi-round conversations.
The knowledge base (represented as a ... | 409 | 19,437 |
storm | knowledge_storm/collaborative_storm/modules/information_insertion_module.py | .py | import dspy
import numpy as np
import re
import traceback
from concurrent.futures import ThreadPoolExecutor, as_completed
from sklearn.metrics.pairwise import cosine_similarity
from typing import List, Union, Dict, Optional
from .collaborative_storm_utils import trim_output_after_hint
from ...dataclass import Knowled... | 425 | 18,794 |
storm | knowledge_storm/collaborative_storm/modules/knowledge_base_summary.py | .py | import dspy
from typing import Union
from ...dataclass import KnowledgeBase
class KnowledgeBaseSummmary(dspy.Signature):
"""Your job is to give brief summary of what's been discussed in a roundtable conversation. Contents are themantically organized into hierarchical sections.
You will be presented with these... | 33 | 1,297 |
storm | knowledge_storm/collaborative_storm/modules/collaborative_storm_utils.py | .py | import dspy
import os
import re
import sys
import toml
from typing import List, Tuple, Dict, Optional, TYPE_CHECKING
if TYPE_CHECKING:
from ..engine import RunnerArgument
from ...interface import Information, Retriever, LMConfigs
from ...logging_wrapper import LoggingWrapper
from ...rm import BingSearch
def extr... | 262 | 9,149 |
storm | knowledge_storm/collaborative_storm/modules/simulate_user.py | .py | import dspy
from typing import List, Union
from .collaborative_storm_utils import extract_and_remove_citations
from ...dataclass import ConversationTurn
from ...storm_wiki.modules.knowledge_curation import AskQuestionWithPersona
class GenSimulatedUserUtterance(dspy.Module):
def __init__(self, engine: Union[dspy.... | 38 | 1,525 |
storm | knowledge_storm/collaborative_storm/modules/grounded_question_answering.py | .py | import dspy
from typing import Union, List
from .callback import BaseCallbackHandler
from .collaborative_storm_utils import (
trim_output_after_hint,
format_search_results,
extract_cited_storm_info,
separate_citations,
)
from ...logging_wrapper import LoggingWrapper
from ...utils import ArticleTextProc... | 164 | 7,594 |
storm | knowledge_storm/collaborative_storm/modules/article_generation.py | .py | import dspy
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Set, Union
from .collaborative_storm_utils import clean_up_section
from ...dataclass import KnowledgeBase, KnowledgeNode
class ArticleGenerationModule(dspy.Module):
"""Use the information collected from the information... | 124 | 5,360 |
storm | knowledge_storm/collaborative_storm/modules/expert_generation.py | .py | import dspy
import re
from typing import Union
class GenerateExpertGeneral(dspy.Signature):
"""You need to select a group of diverse experts who will be suitable to be invited to a roundtable discussion on the given topic.
Each expert should represent a different perspective, role, or affiliation related to t... | 84 | 4,337 |
storm | knowledge_storm/collaborative_storm/modules/grounded_question_generation.py | .py | """
This module handles question generation within the Co-STORM framework, specifically designed to support the Moderator role.
The Moderator generates insightful, thought-provoking questions that introduce new directions into the conversation.
By leveraging uncited or unused snippets of information retrieved during ... | 114 | 5,491 |
storm | knowledge_storm/collaborative_storm/modules/co_storm_agents.py | .py | import dspy
from itertools import zip_longest
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
from typing import List, Optional, TYPE_CHECKING
from .callback import BaseCallbackHandler
from .collaborative_storm_utils import (
extract_storm_info_snippet,
_get_answer_question_module_ins... | 376 | 15,817 |
storm | frontend/demo_light/stoc.py | .py | """https://github.com/arnaudmiribel/stoc"""
import re
import streamlit as st
import unidecode
DISABLE_LINK_CSS = """
<style>
a.toc {
color: inherit;
text-decoration: none; /* no underline */
}
</style>"""
class stoc:
def __init__(self):
self.toc_items = list()
def h1(self, text: str, write... | 140 | 4,714 |
storm | frontend/demo_light/demo_util.py | .py | import base64
import datetime
import json
import os
import re
from typing import Optional
import markdown
import pytz
import streamlit as st
# If you install the source code instead of the `knowledge-storm` package,
# Uncomment the following lines:
# import sys
# sys.path.append('../../')
from knowledge_storm import ... | 678 | 25,314 |
storm | frontend/demo_light/storm.py | .py | import os
script_dir = os.path.dirname(os.path.abspath(__file__))
wiki_root_dir = os.path.dirname(os.path.dirname(script_dir))
import demo_util
from pages_util import MyArticles, CreateNewArticle
from streamlit_float import *
from streamlit_option_menu import option_menu
def main():
global database
st.set_p... | 69 | 2,295 |
storm | frontend/demo_light/pages_util/CreateNewArticle.py | .py | import os
import time
import demo_util
import streamlit as st
from demo_util import (
DemoFileIOHelper,
DemoTextProcessingHelper,
DemoUIHelper,
truncate_filename,
)
def handle_not_started():
if st.session_state["page3_write_article_state"] == "not started":
_, search_form_column, _ = st.c... | 168 | 6,594 |
storm | frontend/demo_light/pages_util/MyArticles.py | .py | import os
import demo_util
import streamlit as st
from demo_util import DemoFileIOHelper, DemoUIHelper
from streamlit_card import card
# set page config and display title
def my_articles_page():
with st.sidebar:
_, return_button_col = st.columns([2, 5])
with return_button_col:
if st.b... | 110 | 4,683 |
storm | examples/storm_examples/run_storm_wiki_mistral.py | .py | """
STORM Wiki pipeline powered by Mistral-7B-Instruct-v0.2 hosted by VLLM server and You.com search engine.
You need to set up the following environment variables to run this script:
- YDC_API_KEY: You.com API key; BING_SEARCH_API_KEY: Bing Search API key, SERPER_API_KEY: Serper API key, BRAVE_API_KEY: Brave API k... | 274 | 11,889 |
storm | examples/storm_examples/run_storm_wiki_gemini.py | .py | """
STORM Wiki pipeline powered by Google Gemini models and search engine.
You need to set up the following environment variables to run this script:
- GOOGLE_API_KEY: Google API key (Can be obtained from https://ai.google.dev/gemini-api/docs/api-key)
- YDC_API_KEY: You.com API key; BING_SEARCH_API_KEY: Bing Se... | 217 | 8,163 |
storm | examples/storm_examples/run_storm_wiki_ollama_with_searxng.py | .py | import os
from argparse import ArgumentParser
from dspy import Example
from knowledge_storm import (
STORMWikiRunnerArguments,
STORMWikiRunner,
STORMWikiLMConfigs,
)
from knowledge_storm.lm import OllamaClient
from knowledge_storm.rm import SearXNG
from knowledge_storm.utils import load_api_key
def main... | 216 | 8,302 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.