修复Pylance类型警告和代码优化
修复类型检查警告: - 为 DatabaseManager 添加正确的类型注解 - 修复 self._database 可能为 None 的所有调用点 - 在使用前添加空检查保护 代码优化: - 删除冗余的 stock_data_manager.py 文件 - 修复 technical_indicators.py 的导入问题 - 修复时间参数类型不匹配问题 - 在 stock_kline_viewer.py 中移除未使用的导入 类型安全改进: - 使用 Optional[MySQLDatabase] 明确空值可能性 - 参数类型从 tuple 改为 Optional[tuple] - 改进错误处理和日志记录 现在所有文件都通过了 Pylance 类型检查!
This commit is contained in:
parent
ab613069b2
commit
6ea0f800bd
@ -34,9 +34,9 @@ class DatabaseManager:
|
|||||||
负责数据库连接、原生SQL操作、事务管理等底层功能
|
负责数据库连接、原生SQL操作、事务管理等底层功能
|
||||||
"""
|
"""
|
||||||
|
|
||||||
_instance = None
|
_instance: Optional['DatabaseManager'] = None
|
||||||
_database = None
|
_database: Optional[MySQLDatabase] = None
|
||||||
_is_connected = False
|
_is_connected: bool = False
|
||||||
|
|
||||||
def __new__(cls):
|
def __new__(cls):
|
||||||
if cls._instance is None:
|
if cls._instance is None:
|
||||||
@ -46,7 +46,7 @@ class DatabaseManager:
|
|||||||
def __init__(self):
|
def __init__(self):
|
||||||
if not hasattr(self, '_initialized'):
|
if not hasattr(self, '_initialized'):
|
||||||
self._initialized = True
|
self._initialized = True
|
||||||
self._database = None
|
self._database: Optional[MySQLDatabase] = None
|
||||||
self._is_connected = False
|
self._is_connected = False
|
||||||
|
|
||||||
@property
|
@property
|
||||||
@ -134,6 +134,10 @@ class DatabaseManager:
|
|||||||
if not self.is_connected():
|
if not self.is_connected():
|
||||||
self.connect()
|
self.connect()
|
||||||
|
|
||||||
|
if self._database is None:
|
||||||
|
logger.error(f"{LOG_PREFIXES['ERROR']} 数据库连接未初始化")
|
||||||
|
return False
|
||||||
|
|
||||||
result = self._database.execute_sql("SELECT VERSION()")
|
result = self._database.execute_sql("SELECT VERSION()")
|
||||||
version = result.fetchone()[0]
|
version = result.fetchone()[0]
|
||||||
logger.info(f"{LOG_PREFIXES['DATABASE']} MySQL版本: {version}")
|
logger.info(f"{LOG_PREFIXES['DATABASE']} MySQL版本: {version}")
|
||||||
@ -198,6 +202,10 @@ class DatabaseManager:
|
|||||||
try:
|
try:
|
||||||
if not self.is_connected():
|
if not self.is_connected():
|
||||||
self.connect()
|
self.connect()
|
||||||
|
|
||||||
|
if self._database is None:
|
||||||
|
logger.error(f"{LOG_PREFIXES['ERROR']} 数据库连接未初始化")
|
||||||
|
return False
|
||||||
|
|
||||||
result = self._database.execute_sql(
|
result = self._database.execute_sql(
|
||||||
"SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = %s AND table_name = %s",
|
"SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = %s AND table_name = %s",
|
||||||
@ -215,6 +223,10 @@ class DatabaseManager:
|
|||||||
try:
|
try:
|
||||||
if not self.is_connected():
|
if not self.is_connected():
|
||||||
self.connect()
|
self.connect()
|
||||||
|
|
||||||
|
if self._database is None:
|
||||||
|
logger.error(f"{LOG_PREFIXES['ERROR']} 数据库连接未初始化")
|
||||||
|
return {}
|
||||||
|
|
||||||
# 获取表结构
|
# 获取表结构
|
||||||
result = self._database.execute_sql(f"DESCRIBE {table_name}")
|
result = self._database.execute_sql(f"DESCRIBE {table_name}")
|
||||||
@ -252,6 +264,10 @@ class DatabaseManager:
|
|||||||
if not self.is_connected():
|
if not self.is_connected():
|
||||||
self.connect()
|
self.connect()
|
||||||
|
|
||||||
|
if self._database is None:
|
||||||
|
logger.error(f"{LOG_PREFIXES['ERROR']} 数据库连接未初始化")
|
||||||
|
return 0
|
||||||
|
|
||||||
success_count = 0
|
success_count = 0
|
||||||
total_batches = (len(data_list) + batch_size - 1) // batch_size
|
total_batches = (len(data_list) + batch_size - 1) // batch_size
|
||||||
|
|
||||||
@ -317,7 +333,7 @@ class DatabaseManager:
|
|||||||
logger.error(f"{LOG_PREFIXES['ERROR']} 清空表失败: {e}")
|
logger.error(f"{LOG_PREFIXES['ERROR']} 清空表失败: {e}")
|
||||||
raise
|
raise
|
||||||
|
|
||||||
def execute_sql(self, sql: str, params: tuple = None) -> Any:
|
def execute_sql(self, sql: str, params: Optional[tuple] = None) -> Any:
|
||||||
"""
|
"""
|
||||||
执行原生SQL
|
执行原生SQL
|
||||||
|
|
||||||
@ -332,6 +348,10 @@ class DatabaseManager:
|
|||||||
if not self.is_connected():
|
if not self.is_connected():
|
||||||
self.connect()
|
self.connect()
|
||||||
|
|
||||||
|
if self._database is None:
|
||||||
|
logger.error(f"{LOG_PREFIXES['ERROR']} 数据库连接未初始化")
|
||||||
|
return None
|
||||||
|
|
||||||
if params:
|
if params:
|
||||||
result = self._database.execute_sql(sql, params)
|
result = self._database.execute_sql(sql, params)
|
||||||
else:
|
else:
|
||||||
|
|||||||
@ -1,326 +0,0 @@
|
|||||||
"""
|
|
||||||
股票数据管理器 - 独立的数据访问层
|
|
||||||
提供股票K线数据的读取、处理和管理功能,屏蔽底层数据库操作细节
|
|
||||||
"""
|
|
||||||
|
|
||||||
import pandas as pd
|
|
||||||
import sys
|
|
||||||
import os
|
|
||||||
import atexit
|
|
||||||
from datetime import datetime
|
|
||||||
|
|
||||||
# 添加路径以导入日志模块
|
|
||||||
current_dir = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
project_root = os.path.dirname(os.path.dirname(current_dir))
|
|
||||||
sys.path.append(project_root)
|
|
||||||
|
|
||||||
# 导入公共配置
|
|
||||||
from common import (
|
|
||||||
normalize_stock_code, get_table_name, get_cache_key,
|
|
||||||
validate_kline_data, KLINE_COLUMNS, LOG_PREFIXES,
|
|
||||||
StockMarket, TimeFrame, DataSource
|
|
||||||
)
|
|
||||||
|
|
||||||
# 导入日志模块
|
|
||||||
try:
|
|
||||||
from src.log.logger import logger
|
|
||||||
except ImportError:
|
|
||||||
import logging
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
logging.basicConfig(level=logging.INFO)
|
|
||||||
|
|
||||||
# 导入数据库相关模块
|
|
||||||
try:
|
|
||||||
from database_config import init_database, get_database
|
|
||||||
from stock_models import create_stock_kline_model
|
|
||||||
except ImportError as e:
|
|
||||||
logger.error(f"{LOG_PREFIXES['ERROR']} 无法导入数据库配置模块: {e}")
|
|
||||||
init_database = None
|
|
||||||
get_database = None
|
|
||||||
create_stock_kline_model = None
|
|
||||||
|
|
||||||
|
|
||||||
class DatabaseConnection:
|
|
||||||
"""
|
|
||||||
数据库连接单例类
|
|
||||||
保持长连接,在程序退出时自动释放
|
|
||||||
"""
|
|
||||||
_instance = None
|
|
||||||
_database = None
|
|
||||||
_is_connected = False
|
|
||||||
|
|
||||||
def __new__(cls):
|
|
||||||
if cls._instance is None:
|
|
||||||
cls._instance = super(DatabaseConnection, cls).__new__(cls)
|
|
||||||
# 注册程序退出时的清理函数
|
|
||||||
atexit.register(cls._cleanup)
|
|
||||||
return cls._instance
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def get_connection(cls):
|
|
||||||
"""获取数据库连接"""
|
|
||||||
instance = cls()
|
|
||||||
if not cls._is_connected:
|
|
||||||
instance._connect()
|
|
||||||
return cls._database
|
|
||||||
|
|
||||||
def _connect(self):
|
|
||||||
"""建立数据库连接"""
|
|
||||||
try:
|
|
||||||
if init_database is None or get_database is None:
|
|
||||||
logger.error(f"{LOG_PREFIXES['ERROR']} 数据库配置函数不可用,请检查database_config模块导入")
|
|
||||||
return False
|
|
||||||
|
|
||||||
if init_database():
|
|
||||||
self.__class__._database = get_database()
|
|
||||||
self.__class__._is_connected = True
|
|
||||||
logger.info(f"{LOG_PREFIXES['SUCCESS']} 数据库连接成功: localhost:3306/qtrade_stock_data")
|
|
||||||
return True
|
|
||||||
else:
|
|
||||||
logger.error(f"{LOG_PREFIXES['ERROR']} 数据库初始化失败")
|
|
||||||
return False
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"{LOG_PREFIXES['ERROR']} 数据库连接异常: {e}")
|
|
||||||
return False
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def _cleanup(cls):
|
|
||||||
"""程序退出时的清理函数"""
|
|
||||||
if cls._database and cls._is_connected:
|
|
||||||
try:
|
|
||||||
cls._database.close()
|
|
||||||
cls._is_connected = False
|
|
||||||
logger.info(f"{LOG_PREFIXES['SUCCESS']} 数据库连接已关闭 (程序退出)")
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"{LOG_PREFIXES['ERROR']} 关闭数据库连接时出错: {e}")
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def is_connected(cls):
|
|
||||||
"""检查连接状态"""
|
|
||||||
return cls._is_connected
|
|
||||||
|
|
||||||
|
|
||||||
class StockDataManager:
|
|
||||||
"""
|
|
||||||
股票数据管理器 - 使用Peewee ORM和数据库连接单例
|
|
||||||
|
|
||||||
职责:
|
|
||||||
1. 提供股票数据的统一访问接口
|
|
||||||
2. 屏蔽底层数据库操作细节
|
|
||||||
3. 实现股票代码标准化和模型缓存
|
|
||||||
4. 提供优雅的错误处理机制
|
|
||||||
5. 使用单例数据库连接,保持长连接
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self):
|
|
||||||
"""
|
|
||||||
初始化数据管理器
|
|
||||||
"""
|
|
||||||
self.db_connection = DatabaseConnection()
|
|
||||||
self.model_cache = {} # 缓存已创建的模型
|
|
||||||
logger.info(f"{LOG_PREFIXES['DATABASE']} StockDataManager (Peewee ORM) 初始化完成")
|
|
||||||
|
|
||||||
def _normalize_stock_code(self, stock_code):
|
|
||||||
"""
|
|
||||||
标准化股票代码格式 - 使用公共配置
|
|
||||||
|
|
||||||
Args:
|
|
||||||
stock_code (str): 股票代码,支持多种格式
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
str: 标准化后的股票代码
|
|
||||||
"""
|
|
||||||
return normalize_stock_code(stock_code)
|
|
||||||
|
|
||||||
def connect_database(self):
|
|
||||||
"""
|
|
||||||
连接数据库(使用单例连接)
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
bool: 连接成功返回True,失败返回False
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
database = DatabaseConnection.get_connection()
|
|
||||||
if database and DatabaseConnection.is_connected():
|
|
||||||
return True
|
|
||||||
else:
|
|
||||||
logger.error(f"{LOG_PREFIXES['ERROR']} 无法获取数据库连接")
|
|
||||||
return False
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"❌ 数据库连接异常: {e}")
|
|
||||||
return False
|
|
||||||
|
|
||||||
def disconnect_database(self):
|
|
||||||
"""
|
|
||||||
断开数据库连接(单例模式下不执行实际断开,保持长连接)
|
|
||||||
只清理模型缓存
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
# 单例模式下不断开连接,只清理缓存
|
|
||||||
# 实际的连接断开在程序结束时自动执行
|
|
||||||
logger.info("✅ 数据库连接已关闭 (Peewee)")
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"❌ 关闭数据库连接时出错: {e}")
|
|
||||||
|
|
||||||
def _get_model_class(self, stock_code, period):
|
|
||||||
"""
|
|
||||||
获取或创建股票K线模型类
|
|
||||||
|
|
||||||
实现模型缓存机制,避免重复创建同一个模型
|
|
||||||
|
|
||||||
Args:
|
|
||||||
stock_code (str): 股票代码(支持短格式如'601658'或完整格式如'601658.SH')
|
|
||||||
period (str): 数据周期
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
Model: Peewee模型类,失败时返回None
|
|
||||||
"""
|
|
||||||
# 标准化股票代码
|
|
||||||
normalized_code = self._normalize_stock_code(stock_code)
|
|
||||||
model_key = f"{normalized_code}_{period}"
|
|
||||||
|
|
||||||
if model_key not in self.model_cache:
|
|
||||||
try:
|
|
||||||
# 检查函数是否可用
|
|
||||||
if create_stock_kline_model is None:
|
|
||||||
logger.error("❌ create_stock_kline_model 函数不可用,请检查stock_models模块导入")
|
|
||||||
return None
|
|
||||||
|
|
||||||
# 创建模型类,使用标准化的股票代码
|
|
||||||
model_class = create_stock_kline_model(normalized_code, period)
|
|
||||||
self.model_cache[model_key] = model_class
|
|
||||||
logger.info(f"📊 创建模型缓存: {model_key}")
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"❌ 创建模型失败: {model_key} - {e}")
|
|
||||||
return None
|
|
||||||
|
|
||||||
return self.model_cache[model_key]
|
|
||||||
|
|
||||||
def read_stock_data(self, stock_code, period='1d', start_date=None, end_date=None):
|
|
||||||
"""
|
|
||||||
从数据库读取股票K线数据 - 使用Peewee ORM
|
|
||||||
|
|
||||||
这是数据访问层的主要接口,上层应用通过此方法获取股票数据
|
|
||||||
|
|
||||||
Args:
|
|
||||||
stock_code (str): 股票代码,支持多种格式:
|
|
||||||
- 短格式:'601658', '000001', '510310'
|
|
||||||
- 完整格式:'601658.SH', '000001.SZ', '510310.SH'
|
|
||||||
period (str): 数据周期,支持 1m, 5m, 15m, 30m, 60m, 1d
|
|
||||||
start_date (str): 开始日期,格式 'YYYY-MM-DD',为None时获取最近数据
|
|
||||||
end_date (str): 结束日期,格式 'YYYY-MM-DD',为None时获取到最新数据
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
pd.DataFrame: 包含OHLCV数据的DataFrame,索引为时间
|
|
||||||
列名:open, high, low, close, volume
|
|
||||||
失败时返回空DataFrame
|
|
||||||
"""
|
|
||||||
if not DatabaseConnection.is_connected():
|
|
||||||
logger.error("❌ 数据库未连接")
|
|
||||||
return pd.DataFrame()
|
|
||||||
|
|
||||||
try:
|
|
||||||
# 获取模型类
|
|
||||||
model_class = self._get_model_class(stock_code, period)
|
|
||||||
if not model_class:
|
|
||||||
logger.error(f"❌ 无法获取模型类: {stock_code} ({period})")
|
|
||||||
return pd.DataFrame()
|
|
||||||
|
|
||||||
logger.info(f"📊 使用Peewee查询: {stock_code} ({period})")
|
|
||||||
|
|
||||||
# 构建查询
|
|
||||||
query = model_class.select()
|
|
||||||
|
|
||||||
# 添加日期条件
|
|
||||||
if start_date:
|
|
||||||
start_datetime = datetime.strptime(start_date, '%Y-%m-%d')
|
|
||||||
query = query.where(model_class.timestamp >= start_datetime)
|
|
||||||
|
|
||||||
if end_date:
|
|
||||||
end_datetime = datetime.strptime(end_date, '%Y-%m-%d')
|
|
||||||
query = query.where(model_class.timestamp <= end_datetime)
|
|
||||||
|
|
||||||
# 按时间排序
|
|
||||||
query = query.order_by(model_class.timestamp.asc())
|
|
||||||
|
|
||||||
# 如果没有指定日期范围,限制获取最近500条数据
|
|
||||||
if not start_date and not end_date:
|
|
||||||
query = query.limit(500)
|
|
||||||
|
|
||||||
logger.info(f"🔍 执行Peewee查询: {stock_code} ({period})")
|
|
||||||
|
|
||||||
# 执行查询并转换为DataFrame
|
|
||||||
results = []
|
|
||||||
for record in query:
|
|
||||||
results.append({
|
|
||||||
'timestamp': record.timestamp,
|
|
||||||
'open': float(record.open_price),
|
|
||||||
'high': float(record.high_price),
|
|
||||||
'low': float(record.low_price),
|
|
||||||
'close': float(record.close_price),
|
|
||||||
'volume': int(record.volume)
|
|
||||||
})
|
|
||||||
|
|
||||||
if not results:
|
|
||||||
logger.warning(f"⚠️ 未找到数据: {stock_code} ({period})")
|
|
||||||
return pd.DataFrame()
|
|
||||||
|
|
||||||
# 转换为DataFrame
|
|
||||||
df = pd.DataFrame(results)
|
|
||||||
df['timestamp'] = pd.to_datetime(df['timestamp'])
|
|
||||||
df.set_index('timestamp', inplace=True)
|
|
||||||
|
|
||||||
# 确保数据类型正确
|
|
||||||
numeric_columns = ['open', 'high', 'low', 'close', 'volume']
|
|
||||||
for col in numeric_columns:
|
|
||||||
df[col] = pd.to_numeric(df[col], errors='coerce')
|
|
||||||
|
|
||||||
logger.info(f"✅ 成功读取 {len(df)} 条数据 (Peewee ORM)")
|
|
||||||
logger.info(f"📈 数据范围: {df.index.min()} 到 {df.index.max()}")
|
|
||||||
|
|
||||||
return df
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"❌ 读取股票数据失败 (Peewee): {e}")
|
|
||||||
import traceback
|
|
||||||
traceback.print_exc()
|
|
||||||
return pd.DataFrame()
|
|
||||||
|
|
||||||
def get_available_stocks(self):
|
|
||||||
"""
|
|
||||||
获取可用的股票代码列表
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
list: 可用的股票代码列表
|
|
||||||
"""
|
|
||||||
# TODO: 实现从数据库中获取所有可用股票代码的逻辑
|
|
||||||
# 这需要查询数据库中存在的所有表名,并解析出股票代码
|
|
||||||
logger.warning("⚠️ get_available_stocks() 方法尚未实现")
|
|
||||||
return []
|
|
||||||
|
|
||||||
def get_available_periods(self, stock_code):
|
|
||||||
"""
|
|
||||||
获取指定股票可用的数据周期
|
|
||||||
|
|
||||||
Args:
|
|
||||||
stock_code (str): 股票代码
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
list: 可用的数据周期列表
|
|
||||||
"""
|
|
||||||
# TODO: 实现从数据库中获取指定股票可用周期的逻辑
|
|
||||||
logger.warning("⚠️ get_available_periods() 方法尚未实现")
|
|
||||||
return ['1d', '1m', '5m', '15m', '30m', '60m']
|
|
||||||
|
|
||||||
def __enter__(self):
|
|
||||||
"""
|
|
||||||
上下文管理器入口
|
|
||||||
"""
|
|
||||||
self.connect_database()
|
|
||||||
return self
|
|
||||||
|
|
||||||
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
||||||
"""
|
|
||||||
上下文管理器出口
|
|
||||||
"""
|
|
||||||
self.disconnect_database()
|
|
||||||
@ -7,7 +7,7 @@ import numpy as np
|
|||||||
import talib
|
import talib
|
||||||
from typing import Dict, Any, Optional, List
|
from typing import Dict, Any, Optional, List
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from stock_data_manager import StockDataManager
|
from stockdata_manager import StockDataManager
|
||||||
import logging
|
import logging
|
||||||
|
|
||||||
# 导入公共配置
|
# 导入公共配置
|
||||||
@ -203,9 +203,17 @@ class TechnicalIndicators:
|
|||||||
if cache_key in self._cache:
|
if cache_key in self._cache:
|
||||||
return self._cache[cache_key]
|
return self._cache[cache_key]
|
||||||
|
|
||||||
|
# 转换时间格式
|
||||||
|
from datetime import datetime
|
||||||
|
start_dt = None
|
||||||
|
end_dt = None
|
||||||
|
if start_time:
|
||||||
|
start_dt = datetime.strptime(start_time, '%Y-%m-%d')
|
||||||
|
if end_time:
|
||||||
|
end_dt = datetime.strptime(end_time, '%Y-%m-%d')
|
||||||
|
|
||||||
# 从数据库获取并缓存
|
# 从数据库获取并缓存
|
||||||
with self.data_manager:
|
df = self.data_manager.read_stock_data(stock_code, period, start_dt, end_dt)
|
||||||
df = self.data_manager.read_stock_data(stock_code, period, start_time, end_time)
|
|
||||||
|
|
||||||
if not df.empty:
|
if not df.empty:
|
||||||
self._cache[cache_key] = df
|
self._cache[cache_key] = df
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user