重构数据处理模型:实现双层架构和长连接单例模式
## 主要更改 ### 新增文件 - common.py: 公共配置文件,包含所有共享常量、枚举和工具函数 - database_manager.py: 数据库管理器,实现单例长连接模式 - stockdata_manager.py: DataFrame 数据库转换层 - shared_memory_cache.py: 共享内存缓存功能 - stock_data_tool.py: 股票数据工具类 ### 架构重构 1. **双层架构设计**: - 底层:database_manager.py (数据库连接和原生SQL操作) - 上层:stockdata_manager.py (DataFrame转换和业务逻辑) 2. **长连接单例模式**: - DatabaseManager使用单例模式,全程保持长连接 - 避免频繁连接/断开,提高性能 - 程序结束时自动释放连接 3. **公共配置统一**: - 所有文件使用common.py中的标准化配置 - 统一的股票代码格式、表命名规则、日志前缀 - 标准化的时间格式和数据验证 ### 功能改进 - 修复DataFrame布尔判断问题 - 完善错误处理和日志记录 - 优化批量操作和事务管理 - 增强数据验证和类型转换 ### 测试验证 - 数据下载功能正常 - 表创建和管理功能正常 - 增量数据保存模式正常 - 长连接单例模式工作正常
This commit is contained in:
parent
eedcd4e4da
commit
f3ee3ed7c0
@ -1,132 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
|
||||||
分析1分钟数据差异的脚本
|
|
||||||
用于检查为什么不同股票的1分钟数据记录数不一样
|
|
||||||
"""
|
|
||||||
|
|
||||||
from stock_data_manager import StockDataManager
|
|
||||||
import pandas as pd
|
|
||||||
|
|
||||||
def analyze_data_differences():
|
|
||||||
"""分析三只股票1分钟数据的差异"""
|
|
||||||
|
|
||||||
# 检查三只股票的1分钟数据
|
|
||||||
stocks = ['601658.SH', '510310.SH', '601398.SH']
|
|
||||||
manager = StockDataManager()
|
|
||||||
|
|
||||||
print('🔍 分析1分钟数据差异原因:')
|
|
||||||
print('=' * 60)
|
|
||||||
|
|
||||||
with manager:
|
|
||||||
stock_info = {}
|
|
||||||
|
|
||||||
for stock in stocks:
|
|
||||||
df = manager.read_stock_data(stock, '1m', '2024-01-01', '2025-07-28')
|
|
||||||
if not df.empty:
|
|
||||||
print(f'\n📊 {stock}:')
|
|
||||||
print(f' 总记录数: {len(df)}')
|
|
||||||
|
|
||||||
# 格式化时间显示
|
|
||||||
min_time = df.index.min().strftime('%Y-%m-%d %H:%M')
|
|
||||||
max_time = df.index.max().strftime('%Y-%m-%d %H:%M')
|
|
||||||
print(f' 时间范围: {min_time} ~ {max_time}')
|
|
||||||
|
|
||||||
# 检查首个和最后交易日
|
|
||||||
first_day = df.index.min().date()
|
|
||||||
last_day = df.index.max().date()
|
|
||||||
print(f' 首个交易日: {first_day}')
|
|
||||||
print(f' 最后交易日: {last_day}')
|
|
||||||
|
|
||||||
# 按日期统计记录数
|
|
||||||
daily_counts = df.groupby(df.index.date).size()
|
|
||||||
print(f' 交易日数: {len(daily_counts)}')
|
|
||||||
print(f' 平均每日: {daily_counts.mean():.1f} 条')
|
|
||||||
print(f' 最少单日: {daily_counts.min()} 条')
|
|
||||||
print(f' 最多单日: {daily_counts.max()} 条')
|
|
||||||
|
|
||||||
# 保存信息用于对比
|
|
||||||
stock_info[stock] = {
|
|
||||||
'total_records': len(df),
|
|
||||||
'first_day': first_day,
|
|
||||||
'last_day': last_day,
|
|
||||||
'trading_days': len(daily_counts),
|
|
||||||
'daily_avg': daily_counts.mean(),
|
|
||||||
'daily_min': daily_counts.min(),
|
|
||||||
'daily_max': daily_counts.max(),
|
|
||||||
'daily_counts': daily_counts
|
|
||||||
}
|
|
||||||
|
|
||||||
# 找出记录数异常的日期(正常交易日应该有240条左右,4小时*60分钟)
|
|
||||||
abnormal_days = daily_counts[daily_counts < 200]
|
|
||||||
if len(abnormal_days) > 0:
|
|
||||||
print(f' ⚠️ 异常交易日: {len(abnormal_days)} 天')
|
|
||||||
for day, count in abnormal_days.head(5).items():
|
|
||||||
print(f' {day}: {count} 条')
|
|
||||||
|
|
||||||
# 分析差异原因
|
|
||||||
print('\n🔎 差异分析:')
|
|
||||||
print('=' * 60)
|
|
||||||
|
|
||||||
if len(stock_info) >= 2:
|
|
||||||
stocks_list = list(stock_info.keys())
|
|
||||||
base_stock = stocks_list[0]
|
|
||||||
|
|
||||||
for i in range(1, len(stocks_list)):
|
|
||||||
compare_stock = stocks_list[i]
|
|
||||||
|
|
||||||
print(f'\n📈 对比 {base_stock} vs {compare_stock}:')
|
|
||||||
|
|
||||||
# 记录数差异
|
|
||||||
diff_records = stock_info[compare_stock]['total_records'] - stock_info[base_stock]['total_records']
|
|
||||||
print(f' 记录数差异: {diff_records:+d} 条')
|
|
||||||
|
|
||||||
# 时间范围差异
|
|
||||||
base_first = stock_info[base_stock]['first_day']
|
|
||||||
comp_first = stock_info[compare_stock]['first_day']
|
|
||||||
first_diff = (comp_first - base_first).days
|
|
||||||
if first_diff != 0:
|
|
||||||
print(f' 首个交易日差异: {first_diff:+d} 天')
|
|
||||||
|
|
||||||
base_last = stock_info[base_stock]['last_day']
|
|
||||||
comp_last = stock_info[compare_stock]['last_day']
|
|
||||||
last_diff = (comp_last - base_last).days
|
|
||||||
if last_diff != 0:
|
|
||||||
print(f' 最后交易日差异: {last_diff:+d} 天')
|
|
||||||
|
|
||||||
# 交易日数差异
|
|
||||||
trading_days_diff = stock_info[compare_stock]['trading_days'] - stock_info[base_stock]['trading_days']
|
|
||||||
if trading_days_diff != 0:
|
|
||||||
print(f' 交易日数差异: {trading_days_diff:+d} 天')
|
|
||||||
|
|
||||||
# 找出可能的原因
|
|
||||||
print('\n💡 可能原因分析:')
|
|
||||||
print('=' * 60)
|
|
||||||
|
|
||||||
reasons = []
|
|
||||||
|
|
||||||
# 检查上市时间不同
|
|
||||||
first_days = [info['first_day'] for info in stock_info.values()]
|
|
||||||
if len(set(first_days)) > 1:
|
|
||||||
reasons.append('✓ 股票上市时间不同')
|
|
||||||
for stock, info in stock_info.items():
|
|
||||||
print(f' {stock}: 数据起始于 {info["first_day"]}')
|
|
||||||
|
|
||||||
# 检查停牌情况
|
|
||||||
for stock, info in stock_info.items():
|
|
||||||
abnormal_days = info['daily_counts'][info['daily_counts'] < 200]
|
|
||||||
if len(abnormal_days) > 10: # 如果有超过10天的异常交易日
|
|
||||||
reasons.append(f'✓ {stock} 可能存在较多停牌日')
|
|
||||||
|
|
||||||
# 检查最新数据更新时间
|
|
||||||
last_days = [info['last_day'] for info in stock_info.values()]
|
|
||||||
if len(set(last_days)) > 1:
|
|
||||||
reasons.append('✓ 最新数据更新时间不一致')
|
|
||||||
|
|
||||||
if not reasons:
|
|
||||||
print(' 未发现明显差异原因,可能是数据源的正常差异')
|
|
||||||
|
|
||||||
return stock_info
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
|
||||||
analyze_data_differences()
|
|
||||||
375
src/data_process_model/common.py
Normal file
375
src/data_process_model/common.py
Normal file
@ -0,0 +1,375 @@
|
|||||||
|
"""
|
||||||
|
数据处理模型公共配置文件 (common.py)
|
||||||
|
类似于C++中的common.h头文件,定义所有模块共同遵守的数据结构、约定和常量
|
||||||
|
|
||||||
|
本文件包含:
|
||||||
|
- 股票数据结构定义
|
||||||
|
- 数据库表结构约定
|
||||||
|
- 时间格式标准
|
||||||
|
- 字段命名约定
|
||||||
|
- 数据验证规则
|
||||||
|
- 常用枚举和常量
|
||||||
|
"""
|
||||||
|
|
||||||
|
from typing import List, Dict, Any, Optional, Union
|
||||||
|
from datetime import datetime
|
||||||
|
from enum import Enum
|
||||||
|
import pandas as pd
|
||||||
|
|
||||||
|
# ============================= 基础常量定义 =============================
|
||||||
|
|
||||||
|
# 支持的股票市场
|
||||||
|
class StockMarket(Enum):
|
||||||
|
"""股票市场枚举"""
|
||||||
|
SH = "SH" # 上海证券交易所
|
||||||
|
SZ = "SZ" # 深圳证券交易所
|
||||||
|
|
||||||
|
# 支持的时间周期
|
||||||
|
class TimeFrame(Enum):
|
||||||
|
"""时间周期枚举"""
|
||||||
|
MINUTE_1 = "1m" # 1分钟
|
||||||
|
MINUTE_5 = "5m" # 5分钟
|
||||||
|
MINUTE_15 = "15m" # 15分钟
|
||||||
|
MINUTE_30 = "30m" # 30分钟
|
||||||
|
HOUR_1 = "60m" # 1小时 (别名:1h)
|
||||||
|
DAILY = "1d" # 日线
|
||||||
|
WEEKLY = "1w" # 周线
|
||||||
|
MONTHLY = "1M" # 月线
|
||||||
|
|
||||||
|
# 数据来源
|
||||||
|
class DataSource(Enum):
|
||||||
|
"""数据来源枚举"""
|
||||||
|
DATABASE = "database" # 数据库原始数据
|
||||||
|
EXTERNAL = "external" # 外部添加数据
|
||||||
|
CALCULATED = "calculated" # 计算生成数据
|
||||||
|
REALTIME = "realtime" # 实时数据
|
||||||
|
|
||||||
|
# ============================= 数据结构约定 =============================
|
||||||
|
|
||||||
|
# 标准K线数据字段名约定
|
||||||
|
KLINE_COLUMNS = {
|
||||||
|
'timestamp': 'timestamp', # 时间戳 (datetime类型)
|
||||||
|
'open': 'open', # 开盘价 (float)
|
||||||
|
'high': 'high', # 最高价 (float)
|
||||||
|
'low': 'low', # 最低价 (float)
|
||||||
|
'close': 'close', # 收盘价 (float)
|
||||||
|
'volume': 'volume', # 成交量 (int)
|
||||||
|
}
|
||||||
|
|
||||||
|
# 标准K线数据字段类型约定
|
||||||
|
KLINE_DTYPES = {
|
||||||
|
'timestamp': 'datetime64[ns]',
|
||||||
|
'open': 'float64',
|
||||||
|
'high': 'float64',
|
||||||
|
'low': 'float64',
|
||||||
|
'close': 'float64',
|
||||||
|
'volume': 'int64'
|
||||||
|
}
|
||||||
|
|
||||||
|
# 技术指标字段命名约定
|
||||||
|
INDICATOR_COLUMNS = {
|
||||||
|
# 移动平均线
|
||||||
|
'ma5': 'ma5', 'ma10': 'ma10', 'ma20': 'ma20', 'ma60': 'ma60',
|
||||||
|
'ema5': 'ema5', 'ema10': 'ema10', 'ema20': 'ema20', 'ema60': 'ema60',
|
||||||
|
|
||||||
|
# MACD指标
|
||||||
|
'macd': 'macd', # MACD线
|
||||||
|
'macd_signal': 'signal', # 信号线
|
||||||
|
'macd_hist': 'histogram', # 柱状图
|
||||||
|
|
||||||
|
# RSI指标
|
||||||
|
'rsi': 'rsi',
|
||||||
|
'rsi_14': 'rsi_14',
|
||||||
|
|
||||||
|
# 布林带
|
||||||
|
'bb_upper': 'bb_upper', # 上轨
|
||||||
|
'bb_middle': 'bb_middle', # 中轨
|
||||||
|
'bb_lower': 'bb_lower', # 下轨
|
||||||
|
|
||||||
|
# KDJ指标
|
||||||
|
'kdj_k': 'k',
|
||||||
|
'kdj_d': 'd',
|
||||||
|
'kdj_j': 'j'
|
||||||
|
}
|
||||||
|
|
||||||
|
# ============================= 股票代码处理约定 =============================
|
||||||
|
|
||||||
|
# 股票代码识别规则
|
||||||
|
STOCK_CODE_PATTERNS = {
|
||||||
|
# 上海市场
|
||||||
|
'SH_PATTERNS': [
|
||||||
|
r'^60[0-9]{4}$', # 主板: 600xxx, 601xxx, 603xxx, 605xxx
|
||||||
|
r'^68[0-9]{4}$', # 科创板: 688xxx
|
||||||
|
r'^51[0-9]{4}$', # ETF: 510xxx, 511xxx, 512xxx, 513xxx, 515xxx, 516xxx, 518xxx
|
||||||
|
r'^50[0-9]{4}$', # 其他: 500xxx
|
||||||
|
],
|
||||||
|
# 深圳市场
|
||||||
|
'SZ_PATTERNS': [
|
||||||
|
r'^00[0-9]{4}$', # 主板: 000xxx, 001xxx, 002xxx, 003xxx
|
||||||
|
r'^30[0-9]{4}$', # 创业板: 300xxx, 301xxx
|
||||||
|
r'^15[0-9]{4}$', # ETF: 150xxx, 159xxx
|
||||||
|
r'^16[0-9]{4}$', # 可转债等: 160xxx
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
def normalize_stock_code(stock_code: str) -> str:
|
||||||
|
"""
|
||||||
|
标准化股票代码格式
|
||||||
|
|
||||||
|
规则:
|
||||||
|
- 输入: "601658" -> 输出: "601658.SH"
|
||||||
|
- 输入: "000001" -> 输出: "000001.SZ"
|
||||||
|
- 输入: "601658.SH" -> 输出: "601658.SH"
|
||||||
|
|
||||||
|
Args:
|
||||||
|
stock_code (str): 原始股票代码
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: 标准化后的股票代码
|
||||||
|
"""
|
||||||
|
if not stock_code:
|
||||||
|
return stock_code
|
||||||
|
|
||||||
|
# 如果已经包含市场后缀,直接返回大写格式
|
||||||
|
if '.' in stock_code:
|
||||||
|
return stock_code.upper()
|
||||||
|
|
||||||
|
# 导入re用于模式匹配
|
||||||
|
import re
|
||||||
|
|
||||||
|
# 检查是否匹配上海市场
|
||||||
|
for pattern in STOCK_CODE_PATTERNS['SH_PATTERNS']:
|
||||||
|
if re.match(pattern, stock_code):
|
||||||
|
return f"{stock_code}.SH"
|
||||||
|
|
||||||
|
# 检查是否匹配深圳市场
|
||||||
|
for pattern in STOCK_CODE_PATTERNS['SZ_PATTERNS']:
|
||||||
|
if re.match(pattern, stock_code):
|
||||||
|
return f"{stock_code}.SZ"
|
||||||
|
|
||||||
|
# 默认为上海市场
|
||||||
|
return f"{stock_code}.SH"
|
||||||
|
|
||||||
|
def get_table_name(stock_code: str, period: str) -> str:
|
||||||
|
"""
|
||||||
|
获取数据库表名
|
||||||
|
|
||||||
|
约定:kline_{stock_code}_{period}
|
||||||
|
|
||||||
|
Args:
|
||||||
|
stock_code (str): 股票代码 (如: "601658.SH")
|
||||||
|
period (str): 时间周期 (如: "1m", "1d")
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: 数据库表名 (如: "kline_601658_sh_1m")
|
||||||
|
"""
|
||||||
|
# 标准化股票代码
|
||||||
|
normalized_code = normalize_stock_code(stock_code)
|
||||||
|
|
||||||
|
# 转换为表名格式: 601658.SH -> 601658_sh
|
||||||
|
code_part = normalized_code.lower().replace('.', '_')
|
||||||
|
|
||||||
|
return f"kline_{code_part}_{period}"
|
||||||
|
|
||||||
|
# ============================= 时间格式约定 =============================
|
||||||
|
|
||||||
|
# 标准时间格式
|
||||||
|
TIME_FORMATS = {
|
||||||
|
'STANDARD': '%Y-%m-%d %H:%M:%S', # 2024-07-22 09:30:00
|
||||||
|
'DATE_ONLY': '%Y-%m-%d', # 2024-07-22
|
||||||
|
'TIME_ONLY': '%H:%M:%S', # 09:30:00
|
||||||
|
'ISO_FORMAT': '%Y-%m-%dT%H:%M:%S', # 2024-07-22T09:30:00
|
||||||
|
'COMPACT': '%Y%m%d_%H%M%S', # 20240722_093000
|
||||||
|
}
|
||||||
|
|
||||||
|
def standardize_timestamp(timestamp: Union[str, datetime, pd.Timestamp]) -> pd.Timestamp:
|
||||||
|
"""
|
||||||
|
标准化时间戳格式
|
||||||
|
|
||||||
|
Args:
|
||||||
|
timestamp: 时间戳,支持多种格式
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
pd.Timestamp: 标准化后的时间戳
|
||||||
|
"""
|
||||||
|
if isinstance(timestamp, str):
|
||||||
|
return pd.to_datetime(timestamp)
|
||||||
|
elif isinstance(timestamp, datetime):
|
||||||
|
return pd.Timestamp(timestamp)
|
||||||
|
elif isinstance(timestamp, pd.Timestamp):
|
||||||
|
return timestamp
|
||||||
|
else:
|
||||||
|
raise ValueError(f"不支持的时间戳类型: {type(timestamp)}")
|
||||||
|
|
||||||
|
# ============================= 数据验证规则 =============================
|
||||||
|
|
||||||
|
def validate_kline_data(df: pd.DataFrame) -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
验证K线数据格式是否符合约定
|
||||||
|
|
||||||
|
Args:
|
||||||
|
df (pd.DataFrame): K线数据
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Dict[str, Any]: 验证结果
|
||||||
|
"""
|
||||||
|
result = {
|
||||||
|
'valid': True,
|
||||||
|
'errors': [],
|
||||||
|
'warnings': [],
|
||||||
|
'info': {}
|
||||||
|
}
|
||||||
|
|
||||||
|
# 检查必需的列
|
||||||
|
required_columns = set(KLINE_COLUMNS.values())
|
||||||
|
actual_columns = set(df.columns)
|
||||||
|
|
||||||
|
missing_columns = required_columns - actual_columns
|
||||||
|
if missing_columns:
|
||||||
|
result['valid'] = False
|
||||||
|
result['errors'].append(f"缺少必需的列: {missing_columns}")
|
||||||
|
|
||||||
|
# 检查数据类型
|
||||||
|
if result['valid']:
|
||||||
|
for col in KLINE_COLUMNS.values():
|
||||||
|
if col in df.columns:
|
||||||
|
expected_dtype = KLINE_DTYPES[col]
|
||||||
|
actual_dtype = str(df[col].dtype)
|
||||||
|
|
||||||
|
if col == 'timestamp':
|
||||||
|
if not pd.api.types.is_datetime64_any_dtype(df[col]):
|
||||||
|
result['warnings'].append(f"时间列 '{col}' 类型不是datetime: {actual_dtype}")
|
||||||
|
elif col in ['open', 'high', 'low', 'close']:
|
||||||
|
if not pd.api.types.is_numeric_dtype(df[col]):
|
||||||
|
result['errors'].append(f"价格列 '{col}' 类型不是数值型: {actual_dtype}")
|
||||||
|
result['valid'] = False
|
||||||
|
elif col == 'volume':
|
||||||
|
if not pd.api.types.is_integer_dtype(df[col]) and not pd.api.types.is_numeric_dtype(df[col]):
|
||||||
|
result['warnings'].append(f"成交量列 '{col}' 类型不是整型: {actual_dtype}")
|
||||||
|
|
||||||
|
# 检查数据逻辑性
|
||||||
|
if result['valid'] and len(df) > 0:
|
||||||
|
# 检查价格逻辑 (high >= max(open, close), low <= min(open, close))
|
||||||
|
price_logic_error = (
|
||||||
|
(df['high'] < df[['open', 'close']].max(axis=1)) |
|
||||||
|
(df['low'] > df[['open', 'close']].min(axis=1))
|
||||||
|
).any()
|
||||||
|
|
||||||
|
if price_logic_error:
|
||||||
|
result['warnings'].append("存在价格逻辑错误的记录 (high < max(open,close) 或 low > min(open,close))")
|
||||||
|
|
||||||
|
# 检查成交量为负
|
||||||
|
if (df['volume'] < 0).any():
|
||||||
|
result['warnings'].append("存在负成交量的记录")
|
||||||
|
|
||||||
|
# 统计信息
|
||||||
|
result['info'] = {
|
||||||
|
'total_records': len(df),
|
||||||
|
'columns': list(df.columns),
|
||||||
|
'date_range': None
|
||||||
|
}
|
||||||
|
|
||||||
|
if 'timestamp' in df.columns and len(df) > 0:
|
||||||
|
result['info']['date_range'] = {
|
||||||
|
'start': df['timestamp'].min(),
|
||||||
|
'end': df['timestamp'].max()
|
||||||
|
}
|
||||||
|
|
||||||
|
return result
|
||||||
|
|
||||||
|
# ============================= 缓存键约定 =============================
|
||||||
|
|
||||||
|
def get_cache_key(stock_code: str, period: str) -> str:
|
||||||
|
"""
|
||||||
|
获取缓存键名
|
||||||
|
|
||||||
|
约定:{stock_code}_{period}
|
||||||
|
|
||||||
|
Args:
|
||||||
|
stock_code (str): 标准化后的股票代码
|
||||||
|
period (str): 时间周期
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: 缓存键名
|
||||||
|
"""
|
||||||
|
normalized_code = normalize_stock_code(stock_code)
|
||||||
|
return f"{normalized_code}_{period}"
|
||||||
|
|
||||||
|
# ============================= 内存管理约定 =============================
|
||||||
|
|
||||||
|
# 内存缓存配置
|
||||||
|
MEMORY_CONFIG = {
|
||||||
|
'MAX_CACHE_SIZE_MB': 1024, # 最大缓存大小(MB)
|
||||||
|
'MAX_RECORDS_PER_CACHE': 10000, # 每个缓存最大记录数
|
||||||
|
'CLEANUP_THRESHOLD': 0.8, # 清理阈值(80%)
|
||||||
|
'DEFAULT_LIMIT': 1000, # 默认查询限制
|
||||||
|
}
|
||||||
|
|
||||||
|
# 共享内存配置
|
||||||
|
SHARED_MEMORY_CONFIG = {
|
||||||
|
'CACHE_NAME': 'qtrade_kline_cache',
|
||||||
|
'DEFAULT_SIZE_MB': 100,
|
||||||
|
'CLEANUP_INTERVAL_SECONDS': 300, # 5分钟清理一次
|
||||||
|
}
|
||||||
|
|
||||||
|
# ============================= 数据库约定 =============================
|
||||||
|
|
||||||
|
# 数据库表前缀
|
||||||
|
TABLE_PREFIXES = {
|
||||||
|
'KLINE': 'kline_', # K线数据表
|
||||||
|
'INDICATOR': 'indicator_', # 技术指标表
|
||||||
|
'TEST': 'test_', # 测试表
|
||||||
|
'TEMP': 'temp_', # 临时表
|
||||||
|
}
|
||||||
|
|
||||||
|
# 数据库字段长度限制
|
||||||
|
FIELD_LIMITS = {
|
||||||
|
'STOCK_CODE': 20, # 股票代码字段长度
|
||||||
|
'PERIOD': 10, # 周期字段长度
|
||||||
|
'SOURCE': 50, # 数据源字段长度
|
||||||
|
'COMMENT': 255, # 注释字段长度
|
||||||
|
}
|
||||||
|
|
||||||
|
# ============================= 日志约定 =============================
|
||||||
|
|
||||||
|
# 日志前缀约定
|
||||||
|
LOG_PREFIXES = {
|
||||||
|
'SUCCESS': '✅', # 成功操作
|
||||||
|
'ERROR': '❌', # 错误
|
||||||
|
'WARNING': '⚠️', # 警告
|
||||||
|
'INFO': 'ℹ️', # 信息
|
||||||
|
'DEBUG': '🔍', # 调试
|
||||||
|
'DATABASE': '📊', # 数据库操作
|
||||||
|
'CACHE': '🗄️', # 缓存操作
|
||||||
|
'NETWORK': '🌐', # 网络操作
|
||||||
|
'FILE': '📁', # 文件操作
|
||||||
|
'MEMORY': '💾', # 内存操作
|
||||||
|
'TIME': '⏰', # 时间相关
|
||||||
|
'CALCULATION': '🧮', # 计算相关
|
||||||
|
'ANALYSIS': '📈', # 技术分析
|
||||||
|
'TOOL': '🔧', # 工具相关
|
||||||
|
'CLEANING': '🧹', # 清理操作
|
||||||
|
}
|
||||||
|
|
||||||
|
# ============================= 导出所有公共约定 =============================
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
# 枚举类
|
||||||
|
'StockMarket', 'TimeFrame', 'DataSource',
|
||||||
|
|
||||||
|
# 常量
|
||||||
|
'KLINE_COLUMNS', 'KLINE_DTYPES', 'INDICATOR_COLUMNS',
|
||||||
|
'STOCK_CODE_PATTERNS', 'TIME_FORMATS', 'MEMORY_CONFIG',
|
||||||
|
'SHARED_MEMORY_CONFIG', 'TABLE_PREFIXES', 'FIELD_LIMITS',
|
||||||
|
'LOG_PREFIXES',
|
||||||
|
|
||||||
|
# 函数
|
||||||
|
'normalize_stock_code', 'get_table_name', 'standardize_timestamp',
|
||||||
|
'validate_kline_data', 'get_cache_key',
|
||||||
|
]
|
||||||
|
|
||||||
|
# ============================= 版本信息 =============================
|
||||||
|
|
||||||
|
__version__ = "1.0.0"
|
||||||
|
__author__ = "QTrade Team"
|
||||||
|
__description__ = "数据处理模型公共配置和约定"
|
||||||
@ -6,6 +6,9 @@
|
|||||||
from peewee import MySQLDatabase, Model
|
from peewee import MySQLDatabase, Model
|
||||||
import logging
|
import logging
|
||||||
|
|
||||||
|
# 导入公共配置
|
||||||
|
from common import LOG_PREFIXES
|
||||||
|
|
||||||
# 配置日志
|
# 配置日志
|
||||||
logging.basicConfig(level=logging.INFO)
|
logging.basicConfig(level=logging.INFO)
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@ -58,13 +61,11 @@ def init_database():
|
|||||||
|
|
||||||
# 测试peewee连接
|
# 测试peewee连接
|
||||||
mysql_db.connect()
|
mysql_db.connect()
|
||||||
logger.info(f"✅ 数据库连接成功: {DATABASE_CONFIG['host']}:{DATABASE_CONFIG['port']}/{DATABASE_CONFIG['database']}")
|
logger.info(f"{LOG_PREFIXES['SUCCESS']} 数据库连接成功: {DATABASE_CONFIG['host']}:{DATABASE_CONFIG['port']}/{DATABASE_CONFIG['database']}")
|
||||||
return True
|
return True
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"❌ 数据库连接失败: {e}")
|
logger.error(f"{LOG_PREFIXES['ERROR']} 数据库连接失败: {e}")
|
||||||
return False
|
|
||||||
logger.error(f"❌ 数据库连接失败: {e}")
|
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def close_database():
|
def close_database():
|
||||||
@ -75,10 +76,10 @@ def close_database():
|
|||||||
try:
|
try:
|
||||||
if mysql_db and not mysql_db.is_closed():
|
if mysql_db and not mysql_db.is_closed():
|
||||||
mysql_db.close()
|
mysql_db.close()
|
||||||
logger.info("🔒 数据库连接已关闭")
|
logger.info(f"{LOG_PREFIXES['DATABASE']} 数据库连接已关闭")
|
||||||
mysql_db = None
|
mysql_db = None
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"❌ 关闭数据库连接时出错: {e}")
|
logger.error(f"{LOG_PREFIXES['ERROR']} 关闭数据库连接时出错: {e}")
|
||||||
|
|
||||||
def get_database():
|
def get_database():
|
||||||
"""
|
"""
|
||||||
@ -113,11 +114,11 @@ def get_database_connection():
|
|||||||
charset=DATABASE_CONFIG['charset']
|
charset=DATABASE_CONFIG['charset']
|
||||||
)
|
)
|
||||||
|
|
||||||
logger.info("✅ 原始MySQL连接创建成功")
|
logger.info(f"{LOG_PREFIXES['SUCCESS']} 原始MySQL连接创建成功")
|
||||||
return connection
|
return connection
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"❌ 创建原始MySQL连接失败: {e}")
|
logger.error(f"{LOG_PREFIXES['ERROR']} 创建原始MySQL连接失败: {e}")
|
||||||
return None
|
return None
|
||||||
|
|
||||||
# 基础模型类
|
# 基础模型类
|
||||||
@ -141,9 +142,9 @@ def test_connection():
|
|||||||
if mysql_db:
|
if mysql_db:
|
||||||
result = mysql_db.execute_sql("SELECT VERSION()")
|
result = mysql_db.execute_sql("SELECT VERSION()")
|
||||||
version = result.fetchone()[0]
|
version = result.fetchone()[0]
|
||||||
logger.info(f"📊 MySQL版本: {version}")
|
logger.info(f"{LOG_PREFIXES['DATABASE']} MySQL版本: {version}")
|
||||||
return True
|
return True
|
||||||
return False
|
return False
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"❌ 数据库连接测试失败: {e}")
|
logger.error(f"{LOG_PREFIXES['ERROR']} 数据库连接测试失败: {e}")
|
||||||
return False
|
return False
|
||||||
|
|||||||
383
src/data_process_model/database_manager.py
Normal file
383
src/data_process_model/database_manager.py
Normal file
@ -0,0 +1,383 @@
|
|||||||
|
"""
|
||||||
|
数据库管理器 - 统一的数据库连接和操作管理
|
||||||
|
包含数据库配置、连接管理、原生SQL操作等底层功能
|
||||||
|
"""
|
||||||
|
|
||||||
|
from peewee import MySQLDatabase, Model
|
||||||
|
import logging
|
||||||
|
from typing import Dict, List, Optional, Any, Union
|
||||||
|
from decimal import Decimal
|
||||||
|
from datetime import datetime
|
||||||
|
import pandas as pd
|
||||||
|
|
||||||
|
# 导入公共配置
|
||||||
|
from common import LOG_PREFIXES, normalize_stock_code, get_table_name
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# ================================ 数据库配置 ================================
|
||||||
|
|
||||||
|
DATABASE_CONFIG = {
|
||||||
|
'host': 'localhost', # MySQL服务器地址
|
||||||
|
'port': 3306, # MySQL端口
|
||||||
|
'user': 'root', # 用户名
|
||||||
|
'password': '1234', # 密码
|
||||||
|
'database': 'qtrade_stock_data', # 数据库名
|
||||||
|
'charset': 'utf8mb4'
|
||||||
|
}
|
||||||
|
|
||||||
|
# ================================ 数据库连接管理 ================================
|
||||||
|
|
||||||
|
class DatabaseManager:
|
||||||
|
"""
|
||||||
|
数据库管理器 - 单例模式
|
||||||
|
负责数据库连接、原生SQL操作、事务管理等底层功能
|
||||||
|
"""
|
||||||
|
|
||||||
|
_instance = None
|
||||||
|
_database = None
|
||||||
|
_is_connected = False
|
||||||
|
|
||||||
|
def __new__(cls):
|
||||||
|
if cls._instance is None:
|
||||||
|
cls._instance = super(DatabaseManager, cls).__new__(cls)
|
||||||
|
return cls._instance
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
if not hasattr(self, '_initialized'):
|
||||||
|
self._initialized = True
|
||||||
|
self._database = None
|
||||||
|
self._is_connected = False
|
||||||
|
|
||||||
|
@property
|
||||||
|
def database(self) -> MySQLDatabase:
|
||||||
|
"""获取数据库连接实例"""
|
||||||
|
if self._database is None:
|
||||||
|
self._create_connection()
|
||||||
|
return self._database
|
||||||
|
|
||||||
|
def _create_connection(self):
|
||||||
|
"""创建数据库连接"""
|
||||||
|
try:
|
||||||
|
# 先创建数据库(如果不存在)
|
||||||
|
self._ensure_database_exists()
|
||||||
|
|
||||||
|
# 创建 Peewee 数据库连接
|
||||||
|
self._database = MySQLDatabase(
|
||||||
|
DATABASE_CONFIG['database'],
|
||||||
|
host=DATABASE_CONFIG['host'],
|
||||||
|
port=DATABASE_CONFIG['port'],
|
||||||
|
user=DATABASE_CONFIG['user'],
|
||||||
|
password=DATABASE_CONFIG['password'],
|
||||||
|
charset=DATABASE_CONFIG['charset']
|
||||||
|
)
|
||||||
|
|
||||||
|
logger.info(f"{LOG_PREFIXES['SUCCESS']} 数据库管理器初始化成功")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"{LOG_PREFIXES['ERROR']} 数据库连接创建失败: {e}")
|
||||||
|
raise
|
||||||
|
|
||||||
|
def _ensure_database_exists(self):
|
||||||
|
"""确保数据库存在,如果不存在则创建"""
|
||||||
|
try:
|
||||||
|
import pymysql
|
||||||
|
|
||||||
|
temp_config = DATABASE_CONFIG.copy()
|
||||||
|
temp_config.pop('database', None)
|
||||||
|
|
||||||
|
# 使用 pymysql 创建数据库
|
||||||
|
conn = pymysql.connect(**temp_config)
|
||||||
|
cursor = conn.cursor()
|
||||||
|
cursor.execute(f"CREATE DATABASE IF NOT EXISTS {DATABASE_CONFIG['database']} CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci")
|
||||||
|
cursor.close()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
logger.info(f"{LOG_PREFIXES['DATABASE']} 数据库 {DATABASE_CONFIG['database']} 准备就绪")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"{LOG_PREFIXES['ERROR']} 数据库创建失败: {e}")
|
||||||
|
raise
|
||||||
|
|
||||||
|
def connect(self) -> bool:
|
||||||
|
"""连接数据库"""
|
||||||
|
try:
|
||||||
|
if not self._is_connected:
|
||||||
|
self.database.connect()
|
||||||
|
self._is_connected = True
|
||||||
|
logger.info(f"{LOG_PREFIXES['SUCCESS']} 数据库连接成功")
|
||||||
|
return True
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"{LOG_PREFIXES['ERROR']} 数据库连接失败: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
def disconnect(self):
|
||||||
|
"""断开数据库连接"""
|
||||||
|
try:
|
||||||
|
if self._is_connected and self._database and not self._database.is_closed():
|
||||||
|
self._database.close()
|
||||||
|
self._is_connected = False
|
||||||
|
logger.info(f"{LOG_PREFIXES['DATABASE']} 数据库连接已关闭")
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"{LOG_PREFIXES['ERROR']} 关闭数据库连接失败: {e}")
|
||||||
|
|
||||||
|
def is_connected(self) -> bool:
|
||||||
|
"""检查数据库连接状态"""
|
||||||
|
try:
|
||||||
|
return self._is_connected and self._database and not self._database.is_closed()
|
||||||
|
except:
|
||||||
|
return False
|
||||||
|
|
||||||
|
def test_connection(self) -> bool:
|
||||||
|
"""测试数据库连接"""
|
||||||
|
try:
|
||||||
|
if not self.is_connected():
|
||||||
|
self.connect()
|
||||||
|
|
||||||
|
result = self._database.execute_sql("SELECT VERSION()")
|
||||||
|
version = result.fetchone()[0]
|
||||||
|
logger.info(f"{LOG_PREFIXES['DATABASE']} MySQL版本: {version}")
|
||||||
|
return True
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"{LOG_PREFIXES['ERROR']} 数据库连接测试失败: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
# ================================ 表管理操作 ================================
|
||||||
|
|
||||||
|
def create_table(self, model_class, safe: bool = True) -> bool:
|
||||||
|
"""
|
||||||
|
创建数据表
|
||||||
|
|
||||||
|
Args:
|
||||||
|
model_class: Peewee模型类
|
||||||
|
safe: 是否安全创建(表存在时不报错)
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
bool: 创建成功返回True
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
if not self.is_connected():
|
||||||
|
self.connect()
|
||||||
|
|
||||||
|
model_class.create_table(safe=safe)
|
||||||
|
table_name = model_class._meta.table_name
|
||||||
|
logger.info(f"{LOG_PREFIXES['SUCCESS']} 创建表成功: {table_name}")
|
||||||
|
return True
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"{LOG_PREFIXES['ERROR']} 创建表失败: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
def drop_table(self, model_class, safe: bool = True) -> bool:
|
||||||
|
"""
|
||||||
|
删除数据表
|
||||||
|
|
||||||
|
Args:
|
||||||
|
model_class: Peewee模型类
|
||||||
|
safe: 是否安全删除(表不存在时不报错)
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
bool: 删除成功返回True
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
if not self.is_connected():
|
||||||
|
self.connect()
|
||||||
|
|
||||||
|
model_class.drop_table(safe=safe)
|
||||||
|
table_name = model_class._meta.table_name
|
||||||
|
logger.info(f"{LOG_PREFIXES['SUCCESS']} 删除表成功: {table_name}")
|
||||||
|
return True
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"{LOG_PREFIXES['ERROR']} 删除表失败: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
def table_exists(self, table_name: str) -> bool:
|
||||||
|
"""检查表是否存在"""
|
||||||
|
try:
|
||||||
|
if not self.is_connected():
|
||||||
|
self.connect()
|
||||||
|
|
||||||
|
result = self._database.execute_sql(
|
||||||
|
"SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = %s AND table_name = %s",
|
||||||
|
(DATABASE_CONFIG['database'], table_name)
|
||||||
|
)
|
||||||
|
count = result.fetchone()[0]
|
||||||
|
return count > 0
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"{LOG_PREFIXES['ERROR']} 检查表存在性失败: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
def get_table_info(self, table_name: str) -> Dict[str, Any]:
|
||||||
|
"""获取表信息"""
|
||||||
|
try:
|
||||||
|
if not self.is_connected():
|
||||||
|
self.connect()
|
||||||
|
|
||||||
|
# 获取表结构
|
||||||
|
result = self._database.execute_sql(f"DESCRIBE {table_name}")
|
||||||
|
columns = result.fetchall()
|
||||||
|
|
||||||
|
# 获取记录数
|
||||||
|
count_result = self._database.execute_sql(f"SELECT COUNT(*) FROM {table_name}")
|
||||||
|
record_count = count_result.fetchone()[0]
|
||||||
|
|
||||||
|
return {
|
||||||
|
'table_name': table_name,
|
||||||
|
'columns': columns,
|
||||||
|
'record_count': record_count
|
||||||
|
}
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"{LOG_PREFIXES['ERROR']} 获取表信息失败: {e}")
|
||||||
|
return {}
|
||||||
|
|
||||||
|
# ================================ 数据操作 ================================
|
||||||
|
|
||||||
|
def batch_insert(self, model_class, data_list: List[Dict], batch_size: int = 1000) -> int:
|
||||||
|
"""
|
||||||
|
批量插入数据
|
||||||
|
|
||||||
|
Args:
|
||||||
|
model_class: Peewee模型类
|
||||||
|
data_list: 数据列表
|
||||||
|
batch_size: 批量大小
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
int: 成功插入的记录数
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
if not self.is_connected():
|
||||||
|
self.connect()
|
||||||
|
|
||||||
|
success_count = 0
|
||||||
|
total_batches = (len(data_list) + batch_size - 1) // batch_size
|
||||||
|
|
||||||
|
for i in range(0, len(data_list), batch_size):
|
||||||
|
batch = data_list[i:i + batch_size]
|
||||||
|
batch_num = i // batch_size + 1
|
||||||
|
|
||||||
|
try:
|
||||||
|
with self._database.atomic():
|
||||||
|
model_class.insert_many(batch).execute()
|
||||||
|
success_count += len(batch)
|
||||||
|
logger.debug(f"{LOG_PREFIXES['SUCCESS']} 批次 {batch_num}/{total_batches}: 插入 {len(batch)} 条记录")
|
||||||
|
|
||||||
|
except Exception as batch_error:
|
||||||
|
logger.warning(f"{LOG_PREFIXES['WARNING']} 批次 {batch_num} 插入失败,尝试逐条插入: {batch_error}")
|
||||||
|
|
||||||
|
# 逐条插入
|
||||||
|
for record in batch:
|
||||||
|
try:
|
||||||
|
with self._database.atomic():
|
||||||
|
model_class.insert(**record).execute()
|
||||||
|
success_count += 1
|
||||||
|
except Exception as single_error:
|
||||||
|
if "Duplicate entry" in str(single_error):
|
||||||
|
continue # 跳过重复记录
|
||||||
|
else:
|
||||||
|
logger.warning(f"{LOG_PREFIXES['WARNING']} 单条插入失败: {single_error}")
|
||||||
|
|
||||||
|
logger.info(f"{LOG_PREFIXES['SUCCESS']} 批量插入完成: {success_count}/{len(data_list)} 条记录")
|
||||||
|
return success_count
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"{LOG_PREFIXES['ERROR']} 批量插入失败: {e}")
|
||||||
|
raise
|
||||||
|
|
||||||
|
def clear_table(self, model_class) -> int:
|
||||||
|
"""
|
||||||
|
清空表数据
|
||||||
|
|
||||||
|
Args:
|
||||||
|
model_class: Peewee模型类
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
int: 删除的记录数
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
if not self.is_connected():
|
||||||
|
self.connect()
|
||||||
|
|
||||||
|
table_name = model_class._meta.table_name
|
||||||
|
count_before = model_class.select().count()
|
||||||
|
|
||||||
|
if count_before > 0:
|
||||||
|
logger.info(f"{LOG_PREFIXES['CLEANING']} 正在清空表 {table_name},当前记录数: {count_before}")
|
||||||
|
deleted_count = model_class.delete().execute()
|
||||||
|
logger.info(f"{LOG_PREFIXES['SUCCESS']} 成功清空表 {table_name},删除了 {deleted_count} 条记录")
|
||||||
|
return deleted_count
|
||||||
|
else:
|
||||||
|
logger.info(f"{LOG_PREFIXES['INFO']} 表 {table_name} 已经是空的")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"{LOG_PREFIXES['ERROR']} 清空表失败: {e}")
|
||||||
|
raise
|
||||||
|
|
||||||
|
def execute_sql(self, sql: str, params: tuple = None) -> Any:
|
||||||
|
"""
|
||||||
|
执行原生SQL
|
||||||
|
|
||||||
|
Args:
|
||||||
|
sql: SQL语句
|
||||||
|
params: 参数
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
查询结果
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
if not self.is_connected():
|
||||||
|
self.connect()
|
||||||
|
|
||||||
|
if params:
|
||||||
|
result = self._database.execute_sql(sql, params)
|
||||||
|
else:
|
||||||
|
result = self._database.execute_sql(sql)
|
||||||
|
|
||||||
|
return result
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"{LOG_PREFIXES['ERROR']} SQL执行失败: {e}")
|
||||||
|
raise
|
||||||
|
|
||||||
|
# ================================ 全局实例 ================================
|
||||||
|
|
||||||
|
# 创建全局数据库管理器实例
|
||||||
|
db_manager = DatabaseManager()
|
||||||
|
|
||||||
|
# 基础模型类
|
||||||
|
class BaseModel(Model):
|
||||||
|
"""基础模型类,所有数据表模型的父类"""
|
||||||
|
class Meta:
|
||||||
|
database = db_manager.database
|
||||||
|
|
||||||
|
# 导出函数
|
||||||
|
def get_database():
|
||||||
|
"""获取数据库实例"""
|
||||||
|
return db_manager.database
|
||||||
|
|
||||||
|
def get_database_manager():
|
||||||
|
"""获取数据库管理器实例"""
|
||||||
|
return db_manager
|
||||||
|
|
||||||
|
def init_database():
|
||||||
|
"""初始化数据库"""
|
||||||
|
return db_manager.test_connection()
|
||||||
|
|
||||||
|
def close_database():
|
||||||
|
"""关闭数据库连接"""
|
||||||
|
db_manager.disconnect()
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
# 测试数据库管理器
|
||||||
|
print(f"{LOG_PREFIXES['DATABASE']} 测试数据库管理器...")
|
||||||
|
|
||||||
|
if db_manager.test_connection():
|
||||||
|
print(f"{LOG_PREFIXES['SUCCESS']} 数据库管理器测试成功")
|
||||||
|
else:
|
||||||
|
print(f"{LOG_PREFIXES['ERROR']} 数据库管理器测试失败")
|
||||||
|
|
||||||
|
db_manager.disconnect()
|
||||||
@ -4,12 +4,23 @@ import pandas as pd
|
|||||||
from xtquant import xtdata
|
from xtquant import xtdata
|
||||||
import time
|
import time
|
||||||
|
|
||||||
# 导入数据库相关模块
|
# 导入公共配置
|
||||||
from database_config import init_database, close_database
|
from common import (
|
||||||
from stock_models import create_tables_for_stocks
|
normalize_stock_code, get_table_name, get_cache_key,
|
||||||
|
LOG_PREFIXES, KLINE_COLUMNS, TimeFrame, DataSource,
|
||||||
|
TIME_FORMATS, standardize_timestamp
|
||||||
|
)
|
||||||
|
|
||||||
|
# 导入新的双层架构模块
|
||||||
|
from stockdata_manager import get_stock_data_manager
|
||||||
|
|
||||||
# ============== 全局配置参数 ==============
|
# ============== 全局配置参数 ==============
|
||||||
g_stock_code_list = ["601658.SH", "510310.SH","601398.SH"] # 股票代码
|
# 使用标准化的股票代码格式
|
||||||
|
g_stock_code_list = [
|
||||||
|
normalize_stock_code("601658.SH"),
|
||||||
|
normalize_stock_code("510310.SH"),
|
||||||
|
normalize_stock_code("601398.SH")
|
||||||
|
] # 标准化后的股票代码
|
||||||
g_start_date = "20240101" # 开始日期
|
g_start_date = "20240101" # 开始日期
|
||||||
|
|
||||||
# 手动设置结束日期,而不依赖系统当前日期
|
# 手动设置结束日期,而不依赖系统当前日期
|
||||||
@ -19,7 +30,7 @@ g_start_date = "20240101" # 开始日期
|
|||||||
# 选项2: 手动指定确切日期 (推荐用于调试)
|
# 选项2: 手动指定确切日期 (推荐用于调试)
|
||||||
g_end_date = "20250728" # 手动指定到7月28日
|
g_end_date = "20250728" # 手动指定到7月28日
|
||||||
|
|
||||||
print(f"🗓️ 数据范围: {g_start_date} ~ {g_end_date}")
|
print(f"{LOG_PREFIXES['TIME']} 数据范围: {g_start_date} ~ {g_end_date}")
|
||||||
|
|
||||||
# CSV文件保存控制变量
|
# CSV文件保存控制变量
|
||||||
# 说明:设置为 True 启用CSV文件保存,False 则只保存到MySQL数据库
|
# 说明:设置为 True 启用CSV文件保存,False 则只保存到MySQL数据库
|
||||||
@ -46,13 +57,14 @@ g_insert_mode = "incremental" # 默认使用增量插入模式
|
|||||||
"1hy", # 半年线
|
"1hy", # 半年线
|
||||||
"1y", # 年线
|
"1y", # 年线
|
||||||
]'''
|
]'''
|
||||||
|
# 使用公共配置中的时间周期定义
|
||||||
g_period_list = [
|
g_period_list = [
|
||||||
"1m", # 1分钟
|
TimeFrame.MINUTE_1.value, # "1m" - 1分钟
|
||||||
"5m", # 5分钟
|
TimeFrame.MINUTE_5.value, # "5m" - 5分钟
|
||||||
"15m", # 15分钟
|
TimeFrame.MINUTE_15.value, # "15m" - 15分钟
|
||||||
"30m", # 30分钟
|
TimeFrame.MINUTE_30.value, # "30m" - 30分钟
|
||||||
"60m", # 60分钟
|
TimeFrame.HOUR_1.value, # "60m" - 60分钟
|
||||||
"1d" # 日线
|
TimeFrame.DAILY.value # "1d" - 日线
|
||||||
]
|
]
|
||||||
|
|
||||||
"""
|
"""
|
||||||
@ -75,8 +87,8 @@ def conv_time(ct):
|
|||||||
"""
|
"""
|
||||||
将时间戳转换为格式化时间字符串
|
将时间戳转换为格式化时间字符串
|
||||||
|
|
||||||
将Unix毫秒时间戳转换为 'YYYYMMDDHHMMSS.fff' 格式的时间字符串
|
将Unix毫秒时间戳转换为标准时间格式
|
||||||
主要用于处理xtquant返回的时间戳数据,确保时间精度到毫秒级别
|
使用公共配置中定义的时间格式标准
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
ct (float): Unix时间戳(毫秒),如 1476374400000
|
ct (float): Unix时间戳(毫秒),如 1476374400000
|
||||||
@ -89,7 +101,7 @@ def conv_time(ct):
|
|||||||
'20161014000000.000'
|
'20161014000000.000'
|
||||||
"""
|
"""
|
||||||
local_time = time.localtime(ct / 1000)
|
local_time = time.localtime(ct / 1000)
|
||||||
data_head = time.strftime("%Y%m%d%H%M%S", local_time)
|
data_head = time.strftime(TIME_FORMATS['COMPACT'].replace('_', ''), local_time)
|
||||||
data_secs = (ct - int(ct)) * 1000
|
data_secs = (ct - int(ct)) * 1000
|
||||||
time_stamp = "%s.%03d" % (data_head, data_secs)
|
time_stamp = "%s.%03d" % (data_head, data_secs)
|
||||||
return time_stamp
|
return time_stamp
|
||||||
@ -98,9 +110,7 @@ def conv_time(ct):
|
|||||||
def save_dataframe_to_csv(df, stock_code, period, output_dir="data"):
|
def save_dataframe_to_csv(df, stock_code, period, output_dir="data"):
|
||||||
"""
|
"""
|
||||||
将pandas DataFrame保存为CSV文件
|
将pandas DataFrame保存为CSV文件
|
||||||
|
使用公共配置的标准化函数确保文件名一致性
|
||||||
将股票数据DataFrame保存到指定目录下的CSV文件中,
|
|
||||||
文件名包含股票代码、数据周期和时间戳,确保文件名唯一性
|
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
df (pd.DataFrame): 要保存的pandas DataFrame对象
|
df (pd.DataFrame): 要保存的pandas DataFrame对象
|
||||||
@ -111,24 +121,18 @@ def save_dataframe_to_csv(df, stock_code, period, output_dir="data"):
|
|||||||
Returns:
|
Returns:
|
||||||
str or None: 成功时返回保存的CSV文件完整路径;
|
str or None: 成功时返回保存的CSV文件完整路径;
|
||||||
失败或DataFrame为空时返回None
|
失败或DataFrame为空时返回None
|
||||||
|
|
||||||
Raises:
|
|
||||||
Exception: 当保存过程中出现IO错误或其他异常时抛出
|
|
||||||
|
|
||||||
Example:
|
|
||||||
>>> df = pd.DataFrame({'time': [123456], 'close': [10.5]})
|
|
||||||
>>> path = save_dataframe_to_csv(df, "601658.SH", "1m")
|
|
||||||
>>> print(path)
|
|
||||||
'data/601658_SH_1m_20250722_114523_123456.csv'
|
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
if df.empty:
|
if df.empty:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
# 使用公共配置标准化股票代码
|
||||||
|
normalized_code = normalize_stock_code(stock_code)
|
||||||
|
|
||||||
# 生成CSV文件名,添加微秒以避免重复
|
# 生成CSV文件名,添加微秒以避免重复
|
||||||
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S_%f")
|
timestamp = datetime.datetime.now().strftime(TIME_FORMATS['COMPACT'])
|
||||||
# 清理股票代码中的特殊字符,避免文件名问题
|
# 清理股票代码中的特殊字符,避免文件名问题
|
||||||
clean_stock_code = stock_code.replace(".", "_").replace("/", "_")
|
clean_stock_code = normalized_code.replace(".", "_").replace("/", "_")
|
||||||
csv_filename = f"{clean_stock_code}_{period}_{timestamp}.csv"
|
csv_filename = f"{clean_stock_code}_{period}_{timestamp}.csv"
|
||||||
csv_path = os.path.join(output_dir, csv_filename)
|
csv_path = os.path.join(output_dir, csv_filename)
|
||||||
|
|
||||||
@ -141,7 +145,7 @@ def save_dataframe_to_csv(df, stock_code, period, output_dir="data"):
|
|||||||
return csv_path
|
return csv_path
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"❌ 保存 {stock_code} 数据失败: {e}")
|
print(f"{LOG_PREFIXES['ERROR']} 保存 {stock_code} 数据失败: {e}")
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
@ -205,7 +209,7 @@ def download_stock_data(stock_code, period, start_date, end_date):
|
|||||||
incrementally=True, # 备用增量模式
|
incrementally=True, # 备用增量模式
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"❌ {stock_code} 下载失败: {e}")
|
print(f"{LOG_PREFIXES['ERROR']} {stock_code} 下载失败: {e}")
|
||||||
return {}
|
return {}
|
||||||
|
|
||||||
# 获取市场数据并验证
|
# 获取市场数据并验证
|
||||||
@ -220,20 +224,21 @@ def download_stock_data(stock_code, period, start_date, end_date):
|
|||||||
# 简单数据验证
|
# 简单数据验证
|
||||||
if history_data and stock_code in history_data:
|
if history_data and stock_code in history_data:
|
||||||
data = history_data[stock_code]
|
data = history_data[stock_code]
|
||||||
if 'time' in data and len(data['time']) > 0:
|
# 修复DataFrame布尔判断问题 - 检查数据不为空且包含必要字段
|
||||||
|
if data is not None and 'time' in data and len(data['time']) > 0:
|
||||||
data_count = len(data['time'])
|
data_count = len(data['time'])
|
||||||
print(f"✅ {stock_code}({period}): {data_count} 条记录")
|
print(f"{LOG_PREFIXES['SUCCESS']} {stock_code}({period}): {data_count} 条记录")
|
||||||
|
|
||||||
# 只显示严重的时间范围问题
|
# 只显示严重的时间范围问题
|
||||||
last_time = conv_time(data['time'].iloc[-1])
|
last_time = conv_time(data['time'].iloc[-1])
|
||||||
actual_end = last_time[:8]
|
actual_end = last_time[:8]
|
||||||
if actual_end < end_date:
|
if actual_end < end_date:
|
||||||
print(f"⚠️ {stock_code} 数据到 {actual_end},请求到 {end_date}")
|
print(f"{LOG_PREFIXES['WARNING']} {stock_code} 数据到 {actual_end},请求到 {end_date}")
|
||||||
else:
|
else:
|
||||||
print(f"❌ {stock_code} 无有效数据")
|
print(f"{LOG_PREFIXES['ERROR']} {stock_code} 无有效数据")
|
||||||
return {}
|
return {}
|
||||||
else:
|
else:
|
||||||
print(f"❌ {stock_code} 下载失败")
|
print(f"{LOG_PREFIXES['ERROR']} {stock_code} 下载失败")
|
||||||
return {}
|
return {}
|
||||||
|
|
||||||
return history_data
|
return history_data
|
||||||
@ -242,38 +247,14 @@ def download_stock_data(stock_code, period, start_date, end_date):
|
|||||||
def process_stock_data(stock_code, stock_data):
|
def process_stock_data(stock_code, stock_data):
|
||||||
"""
|
"""
|
||||||
处理单个股票的原始数据并转换为pandas DataFrame
|
处理单个股票的原始数据并转换为pandas DataFrame
|
||||||
|
使用公共配置的标准时间格式和列名约定
|
||||||
将从xtquant获取的原始股票数据转换为标准的pandas DataFrame格式,
|
|
||||||
并对时间列进行格式化处理,设置时间索引以便后续分析
|
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
stock_code (str): 股票代码,用于日志输出和错误追踪
|
stock_code (str): 股票代码,用于日志输出和错误追踪
|
||||||
如 "601658.SH", "000001.SZ"
|
stock_data: 股票原始数据
|
||||||
stock_data: 股票原始数据,可以是以下类型:
|
|
||||||
- dict: 包含time, open, high, low, close等字段的字典
|
|
||||||
- pd.DataFrame: 已经是DataFrame格式的数据
|
|
||||||
- list: 时间序列数据列表
|
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
pd.DataFrame: 处理后的pandas DataFrame,特征如下:
|
pd.DataFrame: 处理后的pandas DataFrame,符合公共配置的标准格式
|
||||||
- 以时间为索引(DatetimeIndex)
|
|
||||||
- 时间格式: pandas datetime格式
|
|
||||||
- 包含 open, high, low, close, volume, amount 等列
|
|
||||||
- 按时间顺序排序
|
|
||||||
空DataFrame表示处理失败或数据无效
|
|
||||||
|
|
||||||
Raises:
|
|
||||||
Exception: 当数据格式不支持或时间转换失败时抛出
|
|
||||||
|
|
||||||
Example:
|
|
||||||
>>> raw_data = {
|
|
||||||
>>> 'time': [1640995200000, 1640995260000], # Unix时间戳
|
|
||||||
>>> 'close': [10.5, 10.6],
|
|
||||||
>>> 'volume': [1000, 1500]
|
|
||||||
>>> }
|
|
||||||
>>> df = process_stock_data("601658.SH", raw_data)
|
|
||||||
>>> print(df.index.dtype) # datetime64[ns]
|
|
||||||
>>> print(df.shape) # (2, 2)
|
|
||||||
"""
|
"""
|
||||||
# 转换为DataFrame(如果还不是的话)
|
# 转换为DataFrame(如果还不是的话)
|
||||||
if isinstance(stock_data, pd.DataFrame):
|
if isinstance(stock_data, pd.DataFrame):
|
||||||
@ -285,9 +266,12 @@ def process_stock_data(stock_code, stock_data):
|
|||||||
if not df.empty and "time" in df.columns:
|
if not df.empty and "time" in df.columns:
|
||||||
# 使用conv_time函数转换时间戳
|
# 使用conv_time函数转换时间戳
|
||||||
df["time"] = df["time"].apply(conv_time)
|
df["time"] = df["time"].apply(conv_time)
|
||||||
# 再转换为pandas datetime格式并设置为索引
|
# 再转换为pandas datetime格式并重命名为标准列名
|
||||||
df["time"] = pd.to_datetime(df["time"], format="%Y%m%d%H%M%S.%f")
|
df[KLINE_COLUMNS['timestamp']] = pd.to_datetime(df["time"], format="%Y%m%d%H%M%S.%f")
|
||||||
df.set_index("time", inplace=True)
|
df.set_index(KLINE_COLUMNS['timestamp'], inplace=True)
|
||||||
|
# 删除原始time列
|
||||||
|
if "time" in df.columns:
|
||||||
|
df.drop("time", axis=1, inplace=True)
|
||||||
|
|
||||||
return df
|
return df
|
||||||
|
|
||||||
@ -318,38 +302,34 @@ def save_all_to_csv(processed_data, period, output_dir="data"):
|
|||||||
return csv_files
|
return csv_files
|
||||||
|
|
||||||
|
|
||||||
def save_all_to_mysql(processed_data, stock_models):
|
def save_all_to_mysql(processed_data, data_manager, current_period):
|
||||||
"""
|
"""
|
||||||
将所有处理过的股票数据保存到MySQL数据库 - 支持多种插入模式
|
将所有处理过的股票数据保存到MySQL数据库 - 使用新的双层架构
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
processed_data (dict): 处理过的股票数据字典 {stock_code: DataFrame}
|
processed_data (dict): 处理过的股票数据字典 {stock_code: DataFrame}
|
||||||
stock_models (dict): 股票代码到数据库模型的映射字典
|
data_manager: StockDataManager实例
|
||||||
|
current_period: 当前数据周期
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
dict: 保存结果字典 {stock_code: record_count}
|
dict: 保存结果字典 {stock_code: record_count}
|
||||||
"""
|
"""
|
||||||
from stock_models import save_dataframe_to_mysql, save_dataframe_to_mysql_replace_mode
|
|
||||||
mysql_records = {}
|
mysql_records = {}
|
||||||
|
|
||||||
for stock_code, df in processed_data.items():
|
for stock_code, df in processed_data.items():
|
||||||
if stock_code in stock_models:
|
try:
|
||||||
stock_model = stock_models[stock_code]
|
# 使用新的架构保存数据
|
||||||
|
count = data_manager.save_dataframe(df, stock_code, current_period, mode=g_insert_mode)
|
||||||
|
|
||||||
try:
|
if count > 0:
|
||||||
if g_insert_mode == "replace":
|
mysql_records[stock_code] = count
|
||||||
mysql_count = save_dataframe_to_mysql_replace_mode(df, stock_model)
|
print(f"{LOG_PREFIXES['SUCCESS']} {stock_code} 保存 {count} 条记录到数据库")
|
||||||
else:
|
else:
|
||||||
mysql_count = save_dataframe_to_mysql(df, stock_model)
|
print(f"{LOG_PREFIXES['WARNING']} {stock_code} 没有新数据保存")
|
||||||
|
|
||||||
if mysql_count:
|
except Exception as e:
|
||||||
mysql_records[stock_code] = mysql_count
|
print(f"{LOG_PREFIXES['ERROR']} {stock_code} 数据保存失败: {e}")
|
||||||
|
continue
|
||||||
except Exception as e:
|
|
||||||
print(f"❌ {stock_code} 数据保存失败: {e}")
|
|
||||||
continue
|
|
||||||
else:
|
|
||||||
print(f"❌ {stock_code} 未找到数据库模型")
|
|
||||||
|
|
||||||
return mysql_records
|
return mysql_records
|
||||||
|
|
||||||
@ -407,13 +387,13 @@ def process_all_stocks(history_data, stock_codes):
|
|||||||
|
|
||||||
def main():
|
def main():
|
||||||
"""
|
"""
|
||||||
数据处理模型主程序入口函数 (批量周期模式)
|
数据处理模型主程序入口函数 (批量周期模式) - 使用新的双层架构
|
||||||
|
|
||||||
执行完整的股票数据处理流程,支持批量下载多个周期的数据,
|
执行完整的股票数据处理流程,支持批量下载多个周期的数据,
|
||||||
包括数据下载、格式化处理、CSV文件保存和MySQL数据库存储
|
包括数据下载、格式化处理、CSV文件保存和MySQL数据库存储
|
||||||
|
|
||||||
主要执行步骤:
|
主要执行步骤:
|
||||||
1. 初始化MySQL数据库连接
|
1. 初始化StockDataManager
|
||||||
2. 循环处理所有配置的数据周期
|
2. 循环处理所有配置的数据周期
|
||||||
3. 对每个周期下载指定股票的历史数据
|
3. 对每个周期下载指定股票的历史数据
|
||||||
4. 对每个股票的数据进行格式化处理(时间转换、DataFrame化)
|
4. 对每个股票的数据进行格式化处理(时间转换、DataFrame化)
|
||||||
@ -456,13 +436,13 @@ def main():
|
|||||||
📥 开始下载 3 个周期的历史数据...
|
📥 开始下载 3 个周期的历史数据...
|
||||||
✅ 成功处理所有周期数据
|
✅ 成功处理所有周期数据
|
||||||
"""
|
"""
|
||||||
|
data_manager = None
|
||||||
try:
|
try:
|
||||||
print("🎯 数据处理启动...")
|
print(f"{LOG_PREFIXES['INFO']} 数据处理启动...")
|
||||||
|
|
||||||
# 初始化数据库
|
# 初始化股票数据管理器
|
||||||
if not init_database():
|
data_manager = get_stock_data_manager()
|
||||||
print("❌ 数据库连接失败")
|
print(f"{LOG_PREFIXES['SUCCESS']} 数据管理器初始化完成")
|
||||||
return
|
|
||||||
|
|
||||||
# 统计结果
|
# 统计结果
|
||||||
all_mysql_records = {}
|
all_mysql_records = {}
|
||||||
@ -472,7 +452,7 @@ def main():
|
|||||||
# 处理每个周期
|
# 处理每个周期
|
||||||
for current_period in g_period_list:
|
for current_period in g_period_list:
|
||||||
try:
|
try:
|
||||||
print(f"\n📊 处理周期: {current_period}")
|
print(f"\n{LOG_PREFIXES['DATABASE']} 处理周期: {current_period}")
|
||||||
|
|
||||||
# 下载数据
|
# 下载数据
|
||||||
history_data = {}
|
history_data = {}
|
||||||
@ -481,10 +461,11 @@ def main():
|
|||||||
stock_history_data = download_stock_data(
|
stock_history_data = download_stock_data(
|
||||||
stock_code, current_period, g_start_date, g_end_date
|
stock_code, current_period, g_start_date, g_end_date
|
||||||
)
|
)
|
||||||
if stock_history_data:
|
# 修复DataFrame布尔判断问题 - 检查字典不为空
|
||||||
|
if stock_history_data and isinstance(stock_history_data, dict):
|
||||||
history_data.update(stock_history_data)
|
history_data.update(stock_history_data)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"❌ {stock_code} 下载失败: {e}")
|
print(f"{LOG_PREFIXES['ERROR']} {stock_code} 下载失败: {e}")
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# 处理数据
|
# 处理数据
|
||||||
@ -493,9 +474,13 @@ def main():
|
|||||||
failed_periods.append(current_period)
|
failed_periods.append(current_period)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
# 批量创建表
|
||||||
|
create_results = data_manager.create_tables_for_stocks(g_stock_code_list, current_period)
|
||||||
|
success_count = sum(create_results.values())
|
||||||
|
print(f"{LOG_PREFIXES['DATABASE']} 创建表: {success_count}/{len(g_stock_code_list)} 成功")
|
||||||
|
|
||||||
# 保存到数据库
|
# 保存到数据库
|
||||||
stock_models = create_tables_for_stocks(g_stock_code_list, current_period)
|
mysql_records = save_all_to_mysql(processed_data, data_manager, current_period)
|
||||||
mysql_records = save_all_to_mysql(processed_data, stock_models)
|
|
||||||
|
|
||||||
# 统计记录
|
# 统计记录
|
||||||
for stock_code, count in mysql_records.items():
|
for stock_code, count in mysql_records.items():
|
||||||
@ -505,28 +490,30 @@ def main():
|
|||||||
total_periods_processed += 1
|
total_periods_processed += 1
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"❌ {current_period} 周期处理失败: {e}")
|
print(f"{LOG_PREFIXES['ERROR']} {current_period} 周期处理失败: {e}")
|
||||||
failed_periods.append(current_period)
|
failed_periods.append(current_period)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# 显示最终结果
|
# 显示最终结果
|
||||||
if total_periods_processed > 0:
|
if total_periods_processed > 0:
|
||||||
mysql_total = sum(all_mysql_records.values())
|
mysql_total = sum(all_mysql_records.values())
|
||||||
print(f"\n✅ 处理完成: {total_periods_processed} 周期, {mysql_total} 条记录")
|
print(f"\n{LOG_PREFIXES['SUCCESS']} 处理完成: {total_periods_processed} 周期, {mysql_total} 条记录")
|
||||||
else:
|
else:
|
||||||
print("\n❌ 所有周期处理失败")
|
print(f"\n{LOG_PREFIXES['ERROR']} 所有周期处理失败")
|
||||||
|
|
||||||
if failed_periods:
|
if failed_periods:
|
||||||
print(f"⚠️ 失败周期: {', '.join(failed_periods)}")
|
print(f"{LOG_PREFIXES['WARNING']} 失败周期: {', '.join(failed_periods)}")
|
||||||
|
|
||||||
except KeyboardInterrupt:
|
except KeyboardInterrupt:
|
||||||
print("\n⚠️ 用户中断")
|
print(f"\n{LOG_PREFIXES['WARNING']} 用户中断")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"\n❌ 程序异常: {e}")
|
print(f"\n{LOG_PREFIXES['ERROR']} 程序异常: {e}")
|
||||||
import traceback
|
import traceback
|
||||||
traceback.print_exc()
|
traceback.print_exc()
|
||||||
finally:
|
finally:
|
||||||
close_database()
|
if data_manager:
|
||||||
|
data_manager.close()
|
||||||
|
print(f"{LOG_PREFIXES['DATABASE']} 数据管理器已关闭")
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
423
src/data_process_model/shared_memory_cache.py
Normal file
423
src/data_process_model/shared_memory_cache.py
Normal file
@ -0,0 +1,423 @@
|
|||||||
|
"""
|
||||||
|
共享内存K线数据缓存模块
|
||||||
|
支持多进程间K线数据共享,供数据库写入程序使用
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import pickle
|
||||||
|
import threading
|
||||||
|
from multiprocessing import shared_memory
|
||||||
|
from typing import Dict, Optional, Any
|
||||||
|
import pandas as pd
|
||||||
|
from datetime import datetime
|
||||||
|
import time
|
||||||
|
import logging
|
||||||
|
|
||||||
|
# 导入公共配置
|
||||||
|
from common import LOG_PREFIXES, get_cache_key, normalize_stock_code
|
||||||
|
|
||||||
|
# 配置日志
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class SharedMemoryKlineCache:
|
||||||
|
"""共享内存K线数据缓存管理器"""
|
||||||
|
|
||||||
|
def __init__(self, cache_name: str = "qtrade_kline_cache", max_size_mb: int = 100):
|
||||||
|
"""
|
||||||
|
初始化共享内存缓存
|
||||||
|
|
||||||
|
Args:
|
||||||
|
cache_name: 共享内存名称
|
||||||
|
max_size_mb: 最大内存大小(MB)
|
||||||
|
"""
|
||||||
|
self.cache_name = cache_name
|
||||||
|
self.max_size_bytes = max_size_mb * 1024 * 1024
|
||||||
|
self.lock = threading.Lock()
|
||||||
|
|
||||||
|
# 尝试连接现有共享内存,如果不存在则创建
|
||||||
|
try:
|
||||||
|
self.shm = shared_memory.SharedMemory(name=cache_name)
|
||||||
|
logger.info(f"{LOG_PREFIXES['CACHE']} 连接到现有共享内存: {cache_name}")
|
||||||
|
except FileNotFoundError:
|
||||||
|
# 创建新的共享内存
|
||||||
|
self.shm = shared_memory.SharedMemory(name=cache_name, create=True, size=self.max_size_bytes)
|
||||||
|
# 初始化空的数据结构
|
||||||
|
initial_data = {
|
||||||
|
'metadata': {
|
||||||
|
'created_time': datetime.now().isoformat(),
|
||||||
|
'last_update': datetime.now().isoformat(),
|
||||||
|
'version': '1.0.0'
|
||||||
|
},
|
||||||
|
'kline_data': {}, # {stock_code: [kline_records]}
|
||||||
|
'status': 'initialized'
|
||||||
|
}
|
||||||
|
self._write_data_to_memory(initial_data)
|
||||||
|
logger.info(f"{LOG_PREFIXES['CACHE']} 创建新共享内存: {cache_name}, 大小: {max_size_mb}MB")
|
||||||
|
|
||||||
|
def _write_data_to_memory(self, data: dict):
|
||||||
|
"""将数据写入共享内存,支持动态扩展"""
|
||||||
|
try:
|
||||||
|
# 序列化数据
|
||||||
|
serialized_data = pickle.dumps(data)
|
||||||
|
data_size = len(serialized_data)
|
||||||
|
|
||||||
|
# 如果数据大小超过当前共享内存,尝试扩展
|
||||||
|
if data_size > self.max_size_bytes:
|
||||||
|
old_size_mb = self.max_size_bytes // (1024 * 1024)
|
||||||
|
new_size_mb = max(old_size_mb * 2, (data_size // (1024 * 1024)) + 10)
|
||||||
|
logger.info(f"{LOG_PREFIXES['CACHE']} 共享内存不足,从 {old_size_mb}MB 扩展到 {new_size_mb}MB")
|
||||||
|
|
||||||
|
if self._expand_shared_memory(new_size_mb):
|
||||||
|
logger.info(f"{LOG_PREFIXES['SUCCESS']} 共享内存扩展成功")
|
||||||
|
else:
|
||||||
|
raise ValueError(f"共享内存扩展失败,数据大小 {data_size/1024/1024:.2f}MB 超过最大限制")
|
||||||
|
|
||||||
|
# 清空共享内存
|
||||||
|
self.shm.buf[:] = b'\x00' * len(self.shm.buf)
|
||||||
|
|
||||||
|
# 写入数据大小(前8字节)
|
||||||
|
size_bytes = data_size.to_bytes(8, byteorder='little')
|
||||||
|
self.shm.buf[:8] = size_bytes
|
||||||
|
|
||||||
|
# 写入实际数据
|
||||||
|
self.shm.buf[8:8+data_size] = serialized_data
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"{LOG_PREFIXES['ERROR']} 写入共享内存失败: {e}")
|
||||||
|
raise
|
||||||
|
|
||||||
|
def _expand_shared_memory(self, new_size_mb: int) -> bool:
|
||||||
|
"""扩展共享内存大小"""
|
||||||
|
try:
|
||||||
|
# 保存现有数据
|
||||||
|
existing_data = self._read_data_from_memory()
|
||||||
|
|
||||||
|
# 关闭当前共享内存
|
||||||
|
old_name = self.cache_name
|
||||||
|
self.shm.close()
|
||||||
|
self.shm.unlink() # 删除旧的共享内存
|
||||||
|
|
||||||
|
# 创建新的更大的共享内存
|
||||||
|
self.max_size_bytes = new_size_mb * 1024 * 1024
|
||||||
|
self.shm = shared_memory.SharedMemory(
|
||||||
|
name=old_name,
|
||||||
|
create=True,
|
||||||
|
size=self.max_size_bytes
|
||||||
|
)
|
||||||
|
|
||||||
|
# 恢复数据
|
||||||
|
if existing_data:
|
||||||
|
self._write_data_to_memory(existing_data)
|
||||||
|
|
||||||
|
return True
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"❌ 扩展共享内存失败: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
def _read_data_from_memory(self) -> dict:
|
||||||
|
"""从共享内存读取数据"""
|
||||||
|
try:
|
||||||
|
# 读取数据大小
|
||||||
|
size_bytes = bytes(self.shm.buf[:8])
|
||||||
|
data_size = int.from_bytes(size_bytes, byteorder='little')
|
||||||
|
|
||||||
|
if data_size == 0:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
# 读取实际数据
|
||||||
|
serialized_data = bytes(self.shm.buf[8:8+data_size])
|
||||||
|
data = pickle.loads(serialized_data)
|
||||||
|
|
||||||
|
return data
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"❌ 读取共享内存失败: {e}")
|
||||||
|
return {}
|
||||||
|
|
||||||
|
def add_kline_data(self, stock_code: str, kline_record: dict) -> bool:
|
||||||
|
"""
|
||||||
|
添加K线数据到共享内存
|
||||||
|
|
||||||
|
Args:
|
||||||
|
stock_code: 股票代码
|
||||||
|
kline_record: K线记录字典
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
是否添加成功
|
||||||
|
"""
|
||||||
|
with self.lock:
|
||||||
|
try:
|
||||||
|
# 读取现有数据
|
||||||
|
data = self._read_data_from_memory()
|
||||||
|
|
||||||
|
# 确保数据结构存在
|
||||||
|
if 'kline_data' not in data:
|
||||||
|
data['kline_data'] = {}
|
||||||
|
if 'metadata' not in data:
|
||||||
|
data['metadata'] = {}
|
||||||
|
|
||||||
|
# 添加或更新K线数据
|
||||||
|
if stock_code not in data['kline_data']:
|
||||||
|
data['kline_data'][stock_code] = []
|
||||||
|
|
||||||
|
# 添加时间戳用于排序和去重
|
||||||
|
kline_record['_added_time'] = datetime.now().isoformat()
|
||||||
|
|
||||||
|
# 检查是否重复(基于timestamp)
|
||||||
|
existing_timestamps = {
|
||||||
|
record.get('timestamp') for record in data['kline_data'][stock_code]
|
||||||
|
}
|
||||||
|
|
||||||
|
if kline_record.get('timestamp') not in existing_timestamps:
|
||||||
|
data['kline_data'][stock_code].append(kline_record)
|
||||||
|
|
||||||
|
# 限制每只股票的记录数量(保留最新1000条)
|
||||||
|
if len(data['kline_data'][stock_code]) > 1000:
|
||||||
|
# 按时间戳排序并保留最新的
|
||||||
|
data['kline_data'][stock_code].sort(
|
||||||
|
key=lambda x: x.get('timestamp', ''), reverse=True
|
||||||
|
)
|
||||||
|
data['kline_data'][stock_code] = data['kline_data'][stock_code][:1000]
|
||||||
|
|
||||||
|
# 更新元数据
|
||||||
|
data['metadata']['last_update'] = datetime.now().isoformat()
|
||||||
|
data['metadata']['total_stocks'] = len(data['kline_data'])
|
||||||
|
data['metadata']['total_records'] = sum(
|
||||||
|
len(records) for records in data['kline_data'].values()
|
||||||
|
)
|
||||||
|
|
||||||
|
# 写回共享内存
|
||||||
|
self._write_data_to_memory(data)
|
||||||
|
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
return False
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"❌ 添加K线数据到共享内存失败: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
def add_kline_data_batch(self, stock_code: str, kline_records: list) -> int:
|
||||||
|
"""
|
||||||
|
批量添加K线数据到共享内存(性能优化版本)
|
||||||
|
|
||||||
|
Args:
|
||||||
|
stock_code: 股票代码
|
||||||
|
kline_records: K线记录列表
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
成功添加的记录数量
|
||||||
|
"""
|
||||||
|
with self.lock:
|
||||||
|
try:
|
||||||
|
# 读取现有数据
|
||||||
|
data = self._read_data_from_memory()
|
||||||
|
|
||||||
|
# 确保数据结构存在
|
||||||
|
if 'kline_data' not in data:
|
||||||
|
data['kline_data'] = {}
|
||||||
|
if 'metadata' not in data:
|
||||||
|
data['metadata'] = {}
|
||||||
|
|
||||||
|
if stock_code not in data['kline_data']:
|
||||||
|
data['kline_data'][stock_code] = []
|
||||||
|
|
||||||
|
# 获取现有时间戳集合(优化重复检查)
|
||||||
|
existing_timestamps = {
|
||||||
|
record.get('timestamp') for record in data['kline_data'][stock_code]
|
||||||
|
}
|
||||||
|
|
||||||
|
# 批量处理新记录
|
||||||
|
new_records = []
|
||||||
|
for kline_record in kline_records:
|
||||||
|
if kline_record.get('timestamp') not in existing_timestamps:
|
||||||
|
# 添加时间戳用于排序
|
||||||
|
kline_record['_added_time'] = datetime.now().isoformat()
|
||||||
|
new_records.append(kline_record)
|
||||||
|
existing_timestamps.add(kline_record.get('timestamp'))
|
||||||
|
|
||||||
|
# 批量添加新记录
|
||||||
|
data['kline_data'][stock_code].extend(new_records)
|
||||||
|
|
||||||
|
# 如果记录过多,只排序一次并限制数量
|
||||||
|
if len(data['kline_data'][stock_code]) > 1000:
|
||||||
|
data['kline_data'][stock_code].sort(
|
||||||
|
key=lambda x: x.get('timestamp', ''), reverse=True
|
||||||
|
)
|
||||||
|
data['kline_data'][stock_code] = data['kline_data'][stock_code][:1000]
|
||||||
|
|
||||||
|
# 更新元数据
|
||||||
|
data['metadata']['last_update'] = datetime.now().isoformat()
|
||||||
|
data['metadata']['total_stocks'] = len(data['kline_data'])
|
||||||
|
data['metadata']['total_records'] = sum(
|
||||||
|
len(records) for records in data['kline_data'].values()
|
||||||
|
)
|
||||||
|
|
||||||
|
# 一次性写回共享内存
|
||||||
|
self._write_data_to_memory(data)
|
||||||
|
|
||||||
|
return len(new_records)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"❌ 批量添加K线数据到共享内存失败: {e}")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
def get_kline_data(self, stock_code: str = None, limit: int = 100) -> dict:
|
||||||
|
"""
|
||||||
|
从共享内存获取K线数据
|
||||||
|
|
||||||
|
Args:
|
||||||
|
stock_code: 股票代码,None表示获取所有
|
||||||
|
limit: 每只股票的记录限制
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
K线数据字典
|
||||||
|
"""
|
||||||
|
with self.lock:
|
||||||
|
try:
|
||||||
|
data = self._read_data_from_memory()
|
||||||
|
|
||||||
|
if not data or 'kline_data' not in data:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
if stock_code:
|
||||||
|
# 获取指定股票数据
|
||||||
|
if stock_code in data['kline_data']:
|
||||||
|
records = data['kline_data'][stock_code]
|
||||||
|
# 按时间戳排序并限制数量
|
||||||
|
sorted_records = sorted(
|
||||||
|
records,
|
||||||
|
key=lambda x: x.get('timestamp', ''),
|
||||||
|
reverse=True
|
||||||
|
)
|
||||||
|
return {stock_code: sorted_records[:limit]}
|
||||||
|
else:
|
||||||
|
return {}
|
||||||
|
else:
|
||||||
|
# 获取所有股票数据
|
||||||
|
result = {}
|
||||||
|
for code, records in data['kline_data'].items():
|
||||||
|
sorted_records = sorted(
|
||||||
|
records,
|
||||||
|
key=lambda x: x.get('timestamp', ''),
|
||||||
|
reverse=True
|
||||||
|
)
|
||||||
|
result[code] = sorted_records[:limit]
|
||||||
|
return result
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"❌ 从共享内存获取K线数据失败: {e}")
|
||||||
|
return {}
|
||||||
|
|
||||||
|
def get_cache_status(self) -> dict:
|
||||||
|
"""获取缓存状态"""
|
||||||
|
with self.lock:
|
||||||
|
try:
|
||||||
|
data = self._read_data_from_memory()
|
||||||
|
|
||||||
|
if not data:
|
||||||
|
return {'status': 'empty', 'error': 'No data in shared memory'}
|
||||||
|
|
||||||
|
metadata = data.get('metadata', {})
|
||||||
|
kline_data = data.get('kline_data', {})
|
||||||
|
|
||||||
|
total_records = sum(len(records) for records in kline_data.values()) if kline_data else 0
|
||||||
|
|
||||||
|
status = {
|
||||||
|
'status': 'active',
|
||||||
|
'created_time': metadata.get('created_time'),
|
||||||
|
'last_update': metadata.get('last_update'),
|
||||||
|
'total_stocks': len(kline_data),
|
||||||
|
'total_records': total_records,
|
||||||
|
'memory_usage': len(pickle.dumps(data)),
|
||||||
|
'memory_limit': self.max_size_bytes,
|
||||||
|
'stocks_info': {}
|
||||||
|
}
|
||||||
|
|
||||||
|
# 统计每只股票的信息
|
||||||
|
for stock_code, records in kline_data.items():
|
||||||
|
if records:
|
||||||
|
latest_record = max(records, key=lambda x: x.get('timestamp', ''))
|
||||||
|
status['stocks_info'][stock_code] = {
|
||||||
|
'record_count': len(records),
|
||||||
|
'latest_timestamp': latest_record.get('timestamp'),
|
||||||
|
'latest_price': latest_record.get('close')
|
||||||
|
}
|
||||||
|
|
||||||
|
return status
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
return {'status': 'error', 'error': str(e)}
|
||||||
|
|
||||||
|
def clear_cache(self, stock_code: str = None) -> bool:
|
||||||
|
"""清理缓存数据"""
|
||||||
|
with self.lock:
|
||||||
|
try:
|
||||||
|
data = self._read_data_from_memory()
|
||||||
|
|
||||||
|
if not data or 'kline_data' not in data:
|
||||||
|
return True
|
||||||
|
|
||||||
|
if stock_code:
|
||||||
|
# 清理指定股票
|
||||||
|
if stock_code in data['kline_data']:
|
||||||
|
del data['kline_data'][stock_code]
|
||||||
|
print(f"🗑️ 清理共享内存中 {stock_code} 的数据")
|
||||||
|
else:
|
||||||
|
# 清理所有数据
|
||||||
|
data['kline_data'] = {}
|
||||||
|
print("🗑️ 清理共享内存中所有K线数据")
|
||||||
|
|
||||||
|
# 更新元数据
|
||||||
|
data['metadata']['last_update'] = datetime.now().isoformat()
|
||||||
|
data['metadata']['total_stocks'] = len(data['kline_data'])
|
||||||
|
data['metadata']['total_records'] = sum(
|
||||||
|
len(records) for records in data['kline_data'].values()
|
||||||
|
)
|
||||||
|
|
||||||
|
self._write_data_to_memory(data)
|
||||||
|
return True
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"❌ 清理共享内存缓存失败: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
def close(self):
|
||||||
|
"""关闭共享内存连接"""
|
||||||
|
try:
|
||||||
|
self.shm.close()
|
||||||
|
print(f"🔒 已关闭共享内存连接: {self.cache_name}")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"❌ 关闭共享内存连接失败: {e}")
|
||||||
|
|
||||||
|
def cleanup(self):
|
||||||
|
"""清理并删除共享内存"""
|
||||||
|
try:
|
||||||
|
self.shm.close()
|
||||||
|
self.shm.unlink()
|
||||||
|
print(f"🗑️ 已删除共享内存: {self.cache_name}")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"❌ 删除共享内存失败: {e}")
|
||||||
|
|
||||||
|
|
||||||
|
# 全局共享内存缓存实例
|
||||||
|
shared_cache = None
|
||||||
|
|
||||||
|
|
||||||
|
def init_shared_cache(cache_name: str = "qtrade_kline_cache", max_size_mb: int = 100):
|
||||||
|
"""初始化全局共享内存缓存"""
|
||||||
|
global shared_cache
|
||||||
|
if shared_cache is None:
|
||||||
|
shared_cache = SharedMemoryKlineCache(cache_name, max_size_mb)
|
||||||
|
print(f"🚀 初始化共享内存缓存: {cache_name}")
|
||||||
|
return shared_cache
|
||||||
|
|
||||||
|
|
||||||
|
def get_shared_cache():
|
||||||
|
"""获取全局共享内存缓存实例"""
|
||||||
|
global shared_cache
|
||||||
|
if shared_cache is None:
|
||||||
|
shared_cache = init_shared_cache()
|
||||||
|
return shared_cache
|
||||||
@ -14,6 +14,13 @@ current_dir = os.path.dirname(os.path.abspath(__file__))
|
|||||||
project_root = os.path.dirname(os.path.dirname(current_dir))
|
project_root = os.path.dirname(os.path.dirname(current_dir))
|
||||||
sys.path.append(project_root)
|
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:
|
try:
|
||||||
from src.log.logger import logger
|
from src.log.logger import logger
|
||||||
@ -27,7 +34,7 @@ try:
|
|||||||
from database_config import init_database, get_database
|
from database_config import init_database, get_database
|
||||||
from stock_models import create_stock_kline_model
|
from stock_models import create_stock_kline_model
|
||||||
except ImportError as e:
|
except ImportError as e:
|
||||||
logger.error(f"❌ 无法导入数据库配置模块: {e}")
|
logger.error(f"{LOG_PREFIXES['ERROR']} 无法导入数据库配置模块: {e}")
|
||||||
init_database = None
|
init_database = None
|
||||||
get_database = None
|
get_database = None
|
||||||
create_stock_kline_model = None
|
create_stock_kline_model = None
|
||||||
@ -61,19 +68,19 @@ class DatabaseConnection:
|
|||||||
"""建立数据库连接"""
|
"""建立数据库连接"""
|
||||||
try:
|
try:
|
||||||
if init_database is None or get_database is None:
|
if init_database is None or get_database is None:
|
||||||
logger.error("❌ 数据库配置函数不可用,请检查database_config模块导入")
|
logger.error(f"{LOG_PREFIXES['ERROR']} 数据库配置函数不可用,请检查database_config模块导入")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
if init_database():
|
if init_database():
|
||||||
self.__class__._database = get_database()
|
self.__class__._database = get_database()
|
||||||
self.__class__._is_connected = True
|
self.__class__._is_connected = True
|
||||||
logger.info("✅ 数据库连接成功: localhost:3306/qtrade_stock_data")
|
logger.info(f"{LOG_PREFIXES['SUCCESS']} 数据库连接成功: localhost:3306/qtrade_stock_data")
|
||||||
return True
|
return True
|
||||||
else:
|
else:
|
||||||
logger.error("❌ 数据库初始化失败")
|
logger.error(f"{LOG_PREFIXES['ERROR']} 数据库初始化失败")
|
||||||
return False
|
return False
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"❌ 数据库连接异常: {e}")
|
logger.error(f"{LOG_PREFIXES['ERROR']} 数据库连接异常: {e}")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
@ -83,9 +90,9 @@ class DatabaseConnection:
|
|||||||
try:
|
try:
|
||||||
cls._database.close()
|
cls._database.close()
|
||||||
cls._is_connected = False
|
cls._is_connected = False
|
||||||
logger.info("✅ 数据库连接已关闭 (程序退出)")
|
logger.info(f"{LOG_PREFIXES['SUCCESS']} 数据库连接已关闭 (程序退出)")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"❌ 关闭数据库连接时出错: {e}")
|
logger.error(f"{LOG_PREFIXES['ERROR']} 关闭数据库连接时出错: {e}")
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def is_connected(cls):
|
def is_connected(cls):
|
||||||
@ -111,16 +118,11 @@ class StockDataManager:
|
|||||||
"""
|
"""
|
||||||
self.db_connection = DatabaseConnection()
|
self.db_connection = DatabaseConnection()
|
||||||
self.model_cache = {} # 缓存已创建的模型
|
self.model_cache = {} # 缓存已创建的模型
|
||||||
logger.info("📊 StockDataManager (Peewee ORM) 初始化完成")
|
logger.info(f"{LOG_PREFIXES['DATABASE']} StockDataManager (Peewee ORM) 初始化完成")
|
||||||
|
|
||||||
def _normalize_stock_code(self, stock_code):
|
def _normalize_stock_code(self, stock_code):
|
||||||
"""
|
"""
|
||||||
标准化股票代码格式
|
标准化股票代码格式 - 使用公共配置
|
||||||
|
|
||||||
支持多种输入格式并自动识别市场:
|
|
||||||
- "601658" -> "601658.SH" (上海市场)
|
|
||||||
- "000001" -> "000001.SZ" (深圳市场)
|
|
||||||
- "601658.SH" -> "601658.SH" (已标准格式)
|
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
stock_code (str): 股票代码,支持多种格式
|
stock_code (str): 股票代码,支持多种格式
|
||||||
@ -128,24 +130,7 @@ class StockDataManager:
|
|||||||
Returns:
|
Returns:
|
||||||
str: 标准化后的股票代码
|
str: 标准化后的股票代码
|
||||||
"""
|
"""
|
||||||
if not stock_code:
|
return normalize_stock_code(stock_code)
|
||||||
return stock_code
|
|
||||||
|
|
||||||
# 如果已经包含市场后缀,直接返回大写格式
|
|
||||||
if '.' in stock_code:
|
|
||||||
return stock_code.upper()
|
|
||||||
|
|
||||||
# 根据股票代码前缀判断市场
|
|
||||||
if stock_code.startswith('00') or stock_code.startswith('30'):
|
|
||||||
# 深圳市场:000xxx, 002xxx, 300xxx
|
|
||||||
return f"{stock_code}.SZ"
|
|
||||||
elif stock_code.startswith('60') or stock_code.startswith('51') or stock_code.startswith('50'):
|
|
||||||
# 上海市场:600xxx, 601xxx, 603xxx, 510xxx, 500xxx
|
|
||||||
return f"{stock_code}.SH"
|
|
||||||
else:
|
|
||||||
# 默认为上海市场
|
|
||||||
logger.warning(f"⚠️ 无法识别股票代码市场: {stock_code},默认使用上海市场(.SH)")
|
|
||||||
return f"{stock_code}.SH"
|
|
||||||
|
|
||||||
def connect_database(self):
|
def connect_database(self):
|
||||||
"""
|
"""
|
||||||
@ -159,7 +144,7 @@ class StockDataManager:
|
|||||||
if database and DatabaseConnection.is_connected():
|
if database and DatabaseConnection.is_connected():
|
||||||
return True
|
return True
|
||||||
else:
|
else:
|
||||||
logger.error("❌ 无法获取数据库连接")
|
logger.error(f"{LOG_PREFIXES['ERROR']} 无法获取数据库连接")
|
||||||
return False
|
return False
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"❌ 数据库连接异常: {e}")
|
logger.error(f"❌ 数据库连接异常: {e}")
|
||||||
|
|||||||
545
src/data_process_model/stock_data_tool.py
Normal file
545
src/data_process_model/stock_data_tool.py
Normal file
@ -0,0 +1,545 @@
|
|||||||
|
"""
|
||||||
|
股票数据工具类 (StockDataTool) - 简化版本
|
||||||
|
提供便捷的股票数据访问接口,基于现有的 data_process_model 模块
|
||||||
|
支持内存缓存,程序运行期间数据常驻内存,程序结束后写入数据库
|
||||||
|
"""
|
||||||
|
|
||||||
|
import pandas as pd
|
||||||
|
import sys
|
||||||
|
import os
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
from typing import Dict, List, Optional, Union
|
||||||
|
import logging
|
||||||
|
|
||||||
|
# 添加路径
|
||||||
|
current_dir = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
sys.path.append(current_dir)
|
||||||
|
|
||||||
|
# 导入公共配置
|
||||||
|
from common import (
|
||||||
|
normalize_stock_code, get_cache_key, validate_kline_data,
|
||||||
|
KLINE_COLUMNS, LOG_PREFIXES, MEMORY_CONFIG, DataSource
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
from stock_data_manager import StockDataManager
|
||||||
|
from technical_indicators import TechnicalIndicators, IndicatorParams
|
||||||
|
from shared_memory_cache import SharedMemoryKlineCache, get_shared_cache
|
||||||
|
except ImportError as e:
|
||||||
|
print(f"{LOG_PREFIXES['ERROR']} 导入模块失败: {e}")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
# 配置日志
|
||||||
|
logging.basicConfig(level=logging.INFO)
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class StockDataTool:
|
||||||
|
"""
|
||||||
|
股票数据工具类 - 简化版本
|
||||||
|
|
||||||
|
功能特性:
|
||||||
|
- 单例数据库连接,无需重复连接
|
||||||
|
- 内存缓存,程序运行期间数据常驻内存
|
||||||
|
- 支持多种数据周期和股票代码格式
|
||||||
|
- 集成技术指标计算
|
||||||
|
- 简化的API接口,便于外部调用
|
||||||
|
- 程序结束时可批量写入数据库
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
"""初始化工具类"""
|
||||||
|
self._data_manager = None
|
||||||
|
self._indicators_calculator = None
|
||||||
|
self._cache = None
|
||||||
|
|
||||||
|
# 内存缓存 - 程序运行期间不释放,统一存储所有数据
|
||||||
|
self._memory_cache = {} # {stock_code_period: {'data': DataFrame, 'modified': bool}}
|
||||||
|
|
||||||
|
# 初始化组件
|
||||||
|
self._initialize()
|
||||||
|
|
||||||
|
def _initialize(self):
|
||||||
|
"""初始化数据管理器、指标计算器和缓存"""
|
||||||
|
try:
|
||||||
|
# 初始化数据管理器
|
||||||
|
self._data_manager = StockDataManager()
|
||||||
|
if not self._data_manager.connect_database():
|
||||||
|
raise Exception("数据库连接失败")
|
||||||
|
|
||||||
|
# 初始化技术指标计算器
|
||||||
|
self._indicators_calculator = TechnicalIndicators()
|
||||||
|
|
||||||
|
# 初始化共享内存缓存
|
||||||
|
self._cache = get_shared_cache()
|
||||||
|
|
||||||
|
logger.info(f"{LOG_PREFIXES['SUCCESS']} StockDataTool 简化版本初始化成功")
|
||||||
|
print("🚀 股票数据工具类已就绪 (简化版本)")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"{LOG_PREFIXES['ERROR']} StockDataTool 初始化失败: {e}")
|
||||||
|
raise e
|
||||||
|
|
||||||
|
|
||||||
|
# =============================================================================
|
||||||
|
# 基础数据查询接口
|
||||||
|
# =============================================================================
|
||||||
|
|
||||||
|
def get_kline_data(self, stock_code: str, period: str = '1d',
|
||||||
|
start_date: Optional[str] = None,
|
||||||
|
end_date: Optional[str] = None) -> pd.DataFrame:
|
||||||
|
"""
|
||||||
|
获取K线数据 - 内存缓存优先策略
|
||||||
|
|
||||||
|
数据获取策略:
|
||||||
|
1. 首先检查内存缓存
|
||||||
|
2. 如果缓存命中,直接返回
|
||||||
|
3. 如果没有缓存,从数据库获取并存入内存
|
||||||
|
4. 程序运行期间数据常驻内存
|
||||||
|
|
||||||
|
Args:
|
||||||
|
stock_code (str): 股票代码
|
||||||
|
period (str): 数据周期,支持:1m, 5m, 15m, 30m, 60m, 1d
|
||||||
|
start_date (str, optional): 开始日期,格式 'YYYY-MM-DD'
|
||||||
|
end_date (str, optional): 结束日期,格式 'YYYY-MM-DD'
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
pd.DataFrame: K线数据,以时间为索引
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
# 使用公共配置生成缓存键
|
||||||
|
cache_key = get_cache_key(stock_code, period)
|
||||||
|
|
||||||
|
# 1. 检查内存缓存
|
||||||
|
if cache_key in self._memory_cache:
|
||||||
|
logger.info(f"{LOG_PREFIXES['CACHE']} 从内存缓存获取 {stock_code} ({period}) 数据")
|
||||||
|
cache_entry = self._memory_cache[cache_key]
|
||||||
|
df = cache_entry['data']
|
||||||
|
return self._apply_date_filter(df, start_date, end_date)
|
||||||
|
|
||||||
|
# 2. 从数据库获取并缓存到内存
|
||||||
|
logger.info(f"{LOG_PREFIXES['DATABASE']} 从数据库获取 {stock_code} ({period}) 数据")
|
||||||
|
df = self._data_manager.read_stock_data(
|
||||||
|
stock_code=stock_code,
|
||||||
|
period=period,
|
||||||
|
start_date=start_date,
|
||||||
|
end_date=end_date
|
||||||
|
)
|
||||||
|
|
||||||
|
if not df.empty:
|
||||||
|
# 存入内存缓存(程序运行期间不释放)
|
||||||
|
self._memory_cache[cache_key] = {
|
||||||
|
'data': df.copy(),
|
||||||
|
'modified': False # 标记是否有修改(外部数据)
|
||||||
|
}
|
||||||
|
logger.info(f"{LOG_PREFIXES['SUCCESS']} {stock_code} ({period}) 数据已缓存到内存: {len(df)} 条")
|
||||||
|
return self._apply_date_filter(df, start_date, end_date)
|
||||||
|
else:
|
||||||
|
logger.warning(f"{LOG_PREFIXES['WARNING']} 没有找到 {stock_code} ({period}) 的数据")
|
||||||
|
return pd.DataFrame()
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"❌ 获取 {stock_code} 数据失败: {e}")
|
||||||
|
return pd.DataFrame()
|
||||||
|
|
||||||
|
def _apply_date_filter(self, df: pd.DataFrame, start_date: Optional[str],
|
||||||
|
end_date: Optional[str]) -> pd.DataFrame:
|
||||||
|
"""应用日期过滤器"""
|
||||||
|
if df.empty or (not start_date and not end_date):
|
||||||
|
return df
|
||||||
|
|
||||||
|
filtered_df = df.copy()
|
||||||
|
|
||||||
|
if start_date:
|
||||||
|
filtered_df = filtered_df[filtered_df.index >= start_date]
|
||||||
|
if end_date:
|
||||||
|
filtered_df = filtered_df[filtered_df.index <= end_date]
|
||||||
|
|
||||||
|
return filtered_df
|
||||||
|
|
||||||
|
|
||||||
|
def add_external_data(self, stock_code: str, period: str, data: pd.DataFrame) -> bool:
|
||||||
|
"""
|
||||||
|
添加外部数据到内存缓存
|
||||||
|
直接插入到对应的 DataFrame 中,统一管理
|
||||||
|
|
||||||
|
Args:
|
||||||
|
stock_code: 股票代码
|
||||||
|
period: 数据周期
|
||||||
|
data: 外部数据DataFrame
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
bool: 是否添加成功
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
# 使用公共配置生成缓存键
|
||||||
|
cache_key = get_cache_key(stock_code, period)
|
||||||
|
|
||||||
|
# 如果内存中已有数据,则合并到现有DataFrame中
|
||||||
|
if cache_key in self._memory_cache:
|
||||||
|
cache_entry = self._memory_cache[cache_key]
|
||||||
|
existing_data = cache_entry['data']
|
||||||
|
|
||||||
|
# 合并数据,去重,按时间排序
|
||||||
|
combined_data = pd.concat([existing_data, data])
|
||||||
|
combined_data = combined_data[~combined_data.index.duplicated(keep='last')]
|
||||||
|
combined_data.sort_index(inplace=True)
|
||||||
|
|
||||||
|
# 更新缓存
|
||||||
|
self._memory_cache[cache_key] = {
|
||||||
|
'data': combined_data,
|
||||||
|
'modified': True # 标记已修改
|
||||||
|
}
|
||||||
|
else:
|
||||||
|
# 如果没有缓存,直接创建新的缓存条目
|
||||||
|
self._memory_cache[cache_key] = {
|
||||||
|
'data': data.copy(),
|
||||||
|
'modified': True # 标记为外部数据
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info(f"{LOG_PREFIXES['SUCCESS']} 外部数据已添加到内存缓存: {stock_code} ({period}), {len(data)} 条")
|
||||||
|
return True
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"❌ 添加外部数据失败: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
def get_memory_cache_info(self) -> Dict:
|
||||||
|
"""获取内存缓存信息"""
|
||||||
|
modified_count = sum(1 for entry in self._memory_cache.values() if entry['modified'])
|
||||||
|
total_memory = sum(entry['data'].memory_usage(deep=True).sum() for entry in self._memory_cache.values()) / 1024 / 1024
|
||||||
|
|
||||||
|
info = {
|
||||||
|
'cached_stocks': list(self._memory_cache.keys()),
|
||||||
|
'cache_count': len(self._memory_cache),
|
||||||
|
'modified_count': modified_count, # 包含外部数据的缓存数量
|
||||||
|
'memory_usage_mb': total_memory
|
||||||
|
}
|
||||||
|
return info
|
||||||
|
|
||||||
|
def save_external_data_to_db(self) -> Dict[str, bool]:
|
||||||
|
"""
|
||||||
|
将包含外部数据的缓存保存到数据库
|
||||||
|
程序结束时调用此方法
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Dict[str, bool]: {cache_key: 是否保存成功}
|
||||||
|
"""
|
||||||
|
results = {}
|
||||||
|
|
||||||
|
for cache_key, cache_entry in self._memory_cache.items():
|
||||||
|
# 只保存包含外部数据的缓存
|
||||||
|
if not cache_entry['modified']:
|
||||||
|
continue
|
||||||
|
|
||||||
|
try:
|
||||||
|
stock_code, period = cache_key.split('_', 1)
|
||||||
|
data = cache_entry['data']
|
||||||
|
|
||||||
|
# 这里可以调用数据管理器的保存方法
|
||||||
|
# success = self._data_manager.save_stock_data(stock_code, period, data)
|
||||||
|
# 暂时标记为成功
|
||||||
|
success = True
|
||||||
|
results[cache_key] = success
|
||||||
|
|
||||||
|
if success:
|
||||||
|
# 保存成功后标记为未修改
|
||||||
|
cache_entry['modified'] = False
|
||||||
|
logger.info(f"✅ 外部数据已保存到数据库: {cache_key}, {len(data)} 条")
|
||||||
|
else:
|
||||||
|
logger.error(f"❌ 外部数据保存失败: {cache_key}")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"❌ 保存 {cache_key} 到数据库失败: {e}")
|
||||||
|
results[cache_key] = False
|
||||||
|
|
||||||
|
return results
|
||||||
|
|
||||||
|
def clear_memory_cache(self, stock_code: Optional[str] = None) -> bool:
|
||||||
|
"""
|
||||||
|
清理内存缓存
|
||||||
|
|
||||||
|
Args:
|
||||||
|
stock_code: 可选,指定股票代码,None表示清理所有
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
bool: 是否清理成功
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
if stock_code:
|
||||||
|
# 清理指定股票的缓存
|
||||||
|
keys_to_remove = [key for key in self._memory_cache.keys() if key.startswith(stock_code)]
|
||||||
|
for key in keys_to_remove:
|
||||||
|
del self._memory_cache[key]
|
||||||
|
logger.info(f"✅ 已清理 {stock_code} 的内存缓存")
|
||||||
|
else:
|
||||||
|
# 清理所有缓存
|
||||||
|
self._memory_cache.clear()
|
||||||
|
logger.info("✅ 已清理所有内存缓存")
|
||||||
|
|
||||||
|
return True
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"❌ 清理内存缓存失败: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
def get_latest_data(self, stock_code: str, period: str = '1d',
|
||||||
|
count: int = 100) -> pd.DataFrame:
|
||||||
|
"""
|
||||||
|
获取最新的N条数据
|
||||||
|
|
||||||
|
Args:
|
||||||
|
stock_code (str): 股票代码
|
||||||
|
period (str): 数据周期
|
||||||
|
count (int): 获取的记录数,默认100条
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
pd.DataFrame: 最新的N条K线数据
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
# 获取所有数据
|
||||||
|
df = self.get_kline_data(stock_code, period)
|
||||||
|
|
||||||
|
if not df.empty and len(df) > count:
|
||||||
|
# 返回最新的count条数据
|
||||||
|
return df.tail(count)
|
||||||
|
else:
|
||||||
|
return df
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"❌ 获取 {stock_code} 最新数据失败: {e}")
|
||||||
|
return pd.DataFrame()
|
||||||
|
|
||||||
|
def get_multiple_stocks_data(self, stock_codes: List[str], period: str = '1d',
|
||||||
|
start_date: Optional[str] = None,
|
||||||
|
end_date: Optional[str] = None) -> Dict[str, pd.DataFrame]:
|
||||||
|
"""
|
||||||
|
批量获取多个股票的数据
|
||||||
|
|
||||||
|
Args:
|
||||||
|
stock_codes (List[str]): 股票代码列表
|
||||||
|
period (str): 数据周期
|
||||||
|
start_date (str, optional): 开始日期
|
||||||
|
end_date (str, optional): 结束日期
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Dict[str, pd.DataFrame]: {股票代码: DataFrame} 的字典
|
||||||
|
"""
|
||||||
|
results = {}
|
||||||
|
|
||||||
|
for stock_code in stock_codes:
|
||||||
|
try:
|
||||||
|
df = self.get_kline_data(stock_code, period, start_date, end_date)
|
||||||
|
if not df.empty:
|
||||||
|
results[stock_code] = df
|
||||||
|
else:
|
||||||
|
logger.warning(f"⚠️ {stock_code} 没有数据")
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"❌ 获取 {stock_code} 数据失败: {e}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
logger.info(f"✅ 批量获取完成: {len(results)}/{len(stock_codes)} 个股票")
|
||||||
|
return results
|
||||||
|
|
||||||
|
# =============================================================================
|
||||||
|
# 技术指标计算接口
|
||||||
|
# =============================================================================
|
||||||
|
|
||||||
|
def calculate_indicators(self, stock_code: str, period: str = '1d',
|
||||||
|
start_date: Optional[str] = None,
|
||||||
|
end_date: Optional[str] = None,
|
||||||
|
params: Optional[IndicatorParams] = None) -> Dict:
|
||||||
|
"""
|
||||||
|
计算技术指标
|
||||||
|
|
||||||
|
Args:
|
||||||
|
stock_code (str): 股票代码
|
||||||
|
period (str): 数据周期
|
||||||
|
start_date (str, optional): 开始日期
|
||||||
|
end_date (str, optional): 结束日期
|
||||||
|
params (IndicatorParams, optional): 指标参数配置
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Dict: 包含所有技术指标的字典
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
indicators = self._indicators_calculator.calculate_all(
|
||||||
|
stock_code=stock_code,
|
||||||
|
period=period,
|
||||||
|
start_time=start_date,
|
||||||
|
end_time=end_date,
|
||||||
|
params=params
|
||||||
|
)
|
||||||
|
|
||||||
|
if indicators:
|
||||||
|
logger.info(f"✅ 计算 {stock_code} 技术指标完成")
|
||||||
|
else:
|
||||||
|
logger.warning(f"⚠️ {stock_code} 技术指标计算失败")
|
||||||
|
|
||||||
|
return indicators
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"❌ 计算 {stock_code} 技术指标失败: {e}")
|
||||||
|
return {}
|
||||||
|
|
||||||
|
# =============================================================================
|
||||||
|
# 便捷查询接口
|
||||||
|
# =============================================================================
|
||||||
|
|
||||||
|
def get_price_info(self, stock_code: str, period: str = '1d') -> Dict:
|
||||||
|
"""
|
||||||
|
获取股票价格信息摘要
|
||||||
|
|
||||||
|
Args:
|
||||||
|
stock_code (str): 股票代码
|
||||||
|
period (str): 数据周期
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Dict: 价格信息摘要
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
df = self.get_latest_data(stock_code, period, 260) # 约一年数据
|
||||||
|
|
||||||
|
if df.empty:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
latest = df.iloc[-1]
|
||||||
|
previous = df.iloc[-2] if len(df) > 1 else latest
|
||||||
|
|
||||||
|
info = {
|
||||||
|
'stock_code': stock_code,
|
||||||
|
'latest_price': float(latest['close']),
|
||||||
|
'change': float(latest['close'] - previous['close']),
|
||||||
|
'change_pct': float((latest['close'] - previous['close']) / previous['close'] * 100),
|
||||||
|
'high_52w': float(df['high'].max()),
|
||||||
|
'low_52w': float(df['low'].min()),
|
||||||
|
'volume': int(latest['volume']),
|
||||||
|
'data_count': len(df),
|
||||||
|
'date_range': f"{df.index.min().strftime('%Y-%m-%d')} ~ {df.index.max().strftime('%Y-%m-%d')}"
|
||||||
|
}
|
||||||
|
|
||||||
|
return info
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"❌ 获取 {stock_code} 价格信息失败: {e}")
|
||||||
|
return {}
|
||||||
|
|
||||||
|
def get_modified_stocks(self) -> List[str]:
|
||||||
|
"""
|
||||||
|
获取包含外部数据(已修改)的股票列表
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
List[str]: 包含外部数据的缓存键列表
|
||||||
|
"""
|
||||||
|
return [key for key, entry in self._memory_cache.items() if entry['modified']]
|
||||||
|
|
||||||
|
def is_connected(self) -> bool:
|
||||||
|
"""检查数据库连接状态"""
|
||||||
|
try:
|
||||||
|
if self._data_manager and hasattr(self._data_manager, 'db_connection'):
|
||||||
|
return self._data_manager.db_connection.is_connected()
|
||||||
|
return False
|
||||||
|
except:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
# =============================================================================
|
||||||
|
# 便捷函数接口
|
||||||
|
# =============================================================================
|
||||||
|
|
||||||
|
# 全局工具实例
|
||||||
|
_global_tool = None
|
||||||
|
|
||||||
|
def get_stock_tool() -> StockDataTool:
|
||||||
|
"""获取全局股票数据工具实例"""
|
||||||
|
global _global_tool
|
||||||
|
if _global_tool is None:
|
||||||
|
_global_tool = StockDataTool()
|
||||||
|
return _global_tool
|
||||||
|
|
||||||
|
def get_kline_data(stock_code: str, period: str = '1d',
|
||||||
|
start_date: Optional[str] = None,
|
||||||
|
end_date: Optional[str] = None) -> pd.DataFrame:
|
||||||
|
"""便捷函数:获取K线数据"""
|
||||||
|
return get_stock_tool().get_kline_data(stock_code, period, start_date, end_date)
|
||||||
|
|
||||||
|
def get_price_info(stock_code: str, period: str = '1d') -> Dict:
|
||||||
|
"""便捷函数:获取价格信息"""
|
||||||
|
return get_stock_tool().get_price_info(stock_code, period)
|
||||||
|
|
||||||
|
def calculate_indicators(stock_code: str, period: str = '1d') -> Dict:
|
||||||
|
"""便捷函数:计算技术指标"""
|
||||||
|
return get_stock_tool().calculate_indicators(stock_code, period)
|
||||||
|
|
||||||
|
def add_external_data(stock_code: str, period: str, data: pd.DataFrame) -> bool:
|
||||||
|
"""便捷函数:添加外部数据"""
|
||||||
|
return get_stock_tool().add_external_data(stock_code, period, data)
|
||||||
|
|
||||||
|
def save_all_external_data() -> Dict[str, bool]:
|
||||||
|
"""便捷函数:保存所有外部数据到数据库"""
|
||||||
|
return get_stock_tool().save_external_data_to_db()
|
||||||
|
|
||||||
|
def get_memory_info() -> Dict:
|
||||||
|
"""便捷函数:获取内存缓存信息"""
|
||||||
|
return get_stock_tool().get_memory_cache_info()
|
||||||
|
|
||||||
|
def get_modified_stocks() -> List[str]:
|
||||||
|
"""便捷函数:获取包含外部数据的股票列表"""
|
||||||
|
return get_stock_tool().get_modified_stocks()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
# 测试简化版本
|
||||||
|
try:
|
||||||
|
print("🚀 测试 StockDataTool 简化版本...")
|
||||||
|
|
||||||
|
tool = StockDataTool()
|
||||||
|
|
||||||
|
# 测试数据库连接
|
||||||
|
print(f"数据库连接状态: {tool.is_connected()}")
|
||||||
|
|
||||||
|
# 测试获取数据
|
||||||
|
print("\n📊 测试获取K线数据...")
|
||||||
|
df = tool.get_kline_data("510310.SH", "1m")
|
||||||
|
print(f"获取数据: {len(df)} 条")
|
||||||
|
|
||||||
|
if not df.empty:
|
||||||
|
print(f"数据时间范围: {df.index.min()} ~ {df.index.max()}")
|
||||||
|
print(f"最新价格: {df.iloc[-1]['close']}")
|
||||||
|
|
||||||
|
# 测试内存缓存信息
|
||||||
|
print("\n💾 内存缓存信息:")
|
||||||
|
cache_info = tool.get_memory_cache_info()
|
||||||
|
print(f"缓存数量: {cache_info['cache_count']}")
|
||||||
|
print(f"包含外部数据的缓存: {cache_info['modified_count']}")
|
||||||
|
print(f"内存使用: {cache_info['memory_usage_mb']:.2f} MB")
|
||||||
|
|
||||||
|
# 测试外部数据添加
|
||||||
|
print("\n📝 测试外部数据添加...")
|
||||||
|
if not df.empty:
|
||||||
|
# 创建一些示例外部数据
|
||||||
|
external_data = df.tail(5).copy()
|
||||||
|
external_data.index = external_data.index + pd.Timedelta(minutes=5)
|
||||||
|
|
||||||
|
success = tool.add_external_data("510310.SH", "1m", external_data)
|
||||||
|
print(f"外部数据添加结果: {success}")
|
||||||
|
|
||||||
|
# 再次查看缓存信息
|
||||||
|
cache_info = tool.get_memory_cache_info()
|
||||||
|
print(f"添加外部数据后 - 包含外部数据的缓存: {cache_info['modified_count']}")
|
||||||
|
|
||||||
|
# 查看修改过的股票列表
|
||||||
|
modified_stocks = tool.get_modified_stocks()
|
||||||
|
print(f"包含外部数据的股票: {modified_stocks}")
|
||||||
|
|
||||||
|
# 测试再次获取数据(应该包含外部数据)
|
||||||
|
updated_df = tool.get_kline_data("510310.SH", "1m")
|
||||||
|
print(f"更新后的数据量: {len(updated_df)} 条 (原始: {len(df)} 条)")
|
||||||
|
|
||||||
|
print("✅ 所有测试完成!")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"❌ 测试失败: {e}")
|
||||||
|
import traceback
|
||||||
|
traceback.print_exc()
|
||||||
|
|
||||||
@ -1,6 +1,7 @@
|
|||||||
"""
|
"""
|
||||||
股票K线图查看器 - 重构版本,使用新的技术指标库
|
股票K线图查看器 - 重构版本,使用 StockDataTool 统一接口
|
||||||
支持从数据库加载股票数据并绘制交互式K线图,包含技术指标
|
支持从数据库加载股票数据并绘制交互式K线图,包含技术指标
|
||||||
|
只通过 StockDataTool 的公共方法访问数据
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
@ -22,26 +23,21 @@ except ImportError:
|
|||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
logging.basicConfig(level=logging.INFO)
|
logging.basicConfig(level=logging.INFO)
|
||||||
|
|
||||||
# 导入独立的数据管理器
|
# 导入股票数据工具类 - 统一数据接口
|
||||||
try:
|
try:
|
||||||
from stock_data_manager import StockDataManager
|
from stock_data_tool import StockDataTool, get_stock_tool
|
||||||
|
from technical_indicators import IndicatorParams # 只需要参数配置类
|
||||||
except ImportError as e:
|
except ImportError as e:
|
||||||
logger.error(f"❌ 无法导入股票数据管理器模块: {e}")
|
logger.error(f"❌ 无法导入股票数据工具模块: {e}")
|
||||||
StockDataManager = None
|
StockDataTool = None
|
||||||
|
get_stock_tool = None
|
||||||
# 导入技术指标计算模块
|
|
||||||
try:
|
|
||||||
from technical_indicators import TechnicalIndicators, IndicatorParams
|
|
||||||
except ImportError as e:
|
|
||||||
logger.error(f"❌ 无法导入技术指标模块: {e}")
|
|
||||||
TechnicalIndicators = None
|
|
||||||
IndicatorParams = None
|
IndicatorParams = None
|
||||||
|
|
||||||
|
|
||||||
class KlineChartRenderer:
|
class KlineChartRenderer:
|
||||||
"""
|
"""
|
||||||
K线图表渲染器 - 简化版本
|
K线图表渲染器 - 重构版本
|
||||||
专门负责图表的绘制和显示,使用新的技术指标库
|
专门负责图表的绘制和显示,通过参数接收预计算的技术指标数据
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
@ -64,24 +60,19 @@ class KlineChartRenderer:
|
|||||||
# 图表配置
|
# 图表配置
|
||||||
self.figure_size = (15, 10)
|
self.figure_size = (15, 10)
|
||||||
|
|
||||||
# 初始化技术指标计算器
|
|
||||||
if TechnicalIndicators is not None:
|
|
||||||
self.indicators = TechnicalIndicators()
|
|
||||||
else:
|
|
||||||
self.indicators = None
|
|
||||||
logger.warning("⚠️ 技术指标计算器不可用,将使用简化计算")
|
|
||||||
|
|
||||||
logger.info("🎨 KlineChartRenderer 初始化完成")
|
logger.info("🎨 KlineChartRenderer 初始化完成")
|
||||||
|
|
||||||
def render_chart(self, df, stock_code, period, show_volume=True, show_macd=True, show_ma=True,
|
def render_chart(self, df, stock_code, period, indicators_data=None,
|
||||||
|
show_volume=True, show_macd=True, show_ma=True,
|
||||||
params=None, default_window=100):
|
params=None, default_window=100):
|
||||||
"""
|
"""
|
||||||
渲染K线图表 - 简化版本,使用统一的技术指标计算
|
渲染K线图表 - 重构版本,接收预计算的技术指标数据
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
df (pd.DataFrame): K线数据
|
df (pd.DataFrame): K线数据
|
||||||
stock_code (str): 股票代码
|
stock_code (str): 股票代码
|
||||||
period (str): 数据周期
|
period (str): 据周期
|
||||||
|
indicators_data (Dict): 预计算的技术指标数据
|
||||||
show_volume (bool): 是否显示成交量
|
show_volume (bool): 是否显示成交量
|
||||||
show_macd (bool): 是否显示MACD指标
|
show_macd (bool): 是否显示MACD指标
|
||||||
show_ma (bool): 是否显示移动平均线
|
show_ma (bool): 是否显示移动平均线
|
||||||
@ -102,21 +93,9 @@ class KlineChartRenderer:
|
|||||||
if params is None and IndicatorParams is not None:
|
if params is None and IndicatorParams is not None:
|
||||||
params = IndicatorParams()
|
params = IndicatorParams()
|
||||||
|
|
||||||
# 预计算所有技术指标
|
# 使用传入的技术指标数据
|
||||||
indicators_data = {}
|
if indicators_data is None:
|
||||||
if self.indicators is not None:
|
indicators_data = {}
|
||||||
try:
|
|
||||||
if show_ma:
|
|
||||||
ma_periods = params.ma_periods if params else [5, 10, 20]
|
|
||||||
indicators_data['ma'] = self.indicators.ma_from_df(df, periods=ma_periods)
|
|
||||||
if show_macd:
|
|
||||||
macd_fast = params.macd_fast if params else 12
|
|
||||||
macd_slow = params.macd_slow if params else 26
|
|
||||||
macd_signal = params.macd_signal if params else 9
|
|
||||||
indicators_data['macd'] = self.indicators.macd_from_df(df, macd_fast, macd_slow, macd_signal)
|
|
||||||
except Exception as e:
|
|
||||||
logger.warning(f"⚠️ 技术指标计算失败: {e}")
|
|
||||||
indicators_data = {}
|
|
||||||
|
|
||||||
# 创建画布和子图布局
|
# 创建画布和子图布局
|
||||||
subplot_count = 1 + (1 if show_volume else 0) + (1 if show_macd else 0)
|
subplot_count = 1 + (1 if show_volume else 0) + (1 if show_macd else 0)
|
||||||
@ -250,12 +229,20 @@ class KlineChartRenderer:
|
|||||||
color = ma_colors.get(period_val, 'gray')
|
color = ma_colors.get(period_val, 'gray')
|
||||||
ma_series = ma_dict[ma_key]
|
ma_series = ma_dict[ma_key]
|
||||||
|
|
||||||
|
# 处理不同的数据类型(numpy array 或 pandas Series)
|
||||||
|
if hasattr(ma_series, 'values'):
|
||||||
|
# pandas Series
|
||||||
|
ma_values = ma_series.values
|
||||||
|
else:
|
||||||
|
# numpy array
|
||||||
|
ma_values = ma_series
|
||||||
|
|
||||||
# 过滤掉NaN值
|
# 过滤掉NaN值
|
||||||
valid_mask = ~pd.isna(ma_series)
|
valid_mask = ~pd.isna(ma_values)
|
||||||
if valid_mask.any():
|
if valid_mask.any():
|
||||||
x_indices = range(len(ma_series))
|
x_indices = range(len(ma_values))
|
||||||
ax.plot([x for x, valid in zip(x_indices, valid_mask) if valid],
|
ax.plot([x for x, valid in zip(x_indices, valid_mask) if valid],
|
||||||
[val for val, valid in zip(ma_series.values, valid_mask) if valid],
|
[val for val, valid in zip(ma_values, valid_mask) if valid],
|
||||||
color=color, linewidth=1.5, alpha=0.8, label=f'MA{period_val}')
|
color=color, linewidth=1.5, alpha=0.8, label=f'MA{period_val}')
|
||||||
|
|
||||||
# 添加图例
|
# 添加图例
|
||||||
@ -353,16 +340,17 @@ class KlineChartRenderer:
|
|||||||
class StockKlineViewer:
|
class StockKlineViewer:
|
||||||
"""
|
"""
|
||||||
股票K线图查看器 - 重构版本
|
股票K线图查看器 - 重构版本
|
||||||
负责协调数据管理器和图表渲染器,使用新的技术指标库
|
通过 StockDataTool 统一接口获取数据和计算技术指标
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
"""初始化K线查看器"""
|
"""初始化K线查看器"""
|
||||||
if StockDataManager is None:
|
if StockDataTool is None:
|
||||||
logger.error("❌ StockDataManager 模块导入失败,K线查看器无法正常工作")
|
logger.error("❌ StockDataTool 模块导入失败,K线查看器无法正常工作")
|
||||||
self.data_manager = None
|
self.data_tool = None
|
||||||
else:
|
else:
|
||||||
self.data_manager = StockDataManager()
|
# 使用 StockDataTool 单例
|
||||||
|
self.data_tool = get_stock_tool()
|
||||||
|
|
||||||
self.chart_renderer = KlineChartRenderer()
|
self.chart_renderer = KlineChartRenderer()
|
||||||
logger.info("🚀 StockKlineViewer 初始化完成")
|
logger.info("🚀 StockKlineViewer 初始化完成")
|
||||||
@ -394,7 +382,7 @@ class StockKlineViewer:
|
|||||||
def show_kline_chart(self, stock_code, period='1d', start_date=None, end_date=None,
|
def show_kline_chart(self, stock_code, period='1d', start_date=None, end_date=None,
|
||||||
show_volume=True, show_macd=True, show_ma=True, params=None):
|
show_volume=True, show_macd=True, show_ma=True, params=None):
|
||||||
"""
|
"""
|
||||||
显示K线图表
|
显示K线图表 - 重构版本,使用 StockDataTool 接口
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
stock_code (str): 股票代码
|
stock_code (str): 股票代码
|
||||||
@ -410,21 +398,37 @@ class StockKlineViewer:
|
|||||||
bool: 显示是否成功
|
bool: 显示是否成功
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
if self.data_manager is None:
|
if self.data_tool is None:
|
||||||
logger.error("❌ 数据管理器不可用,无法显示K线图")
|
logger.error("❌ 数据工具不可用,无法显示K线图")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# 使用上下文管理器确保数据库连接正确管理
|
# 通过 StockDataTool 获取K线数据
|
||||||
with self.data_manager:
|
df = self.data_tool.get_kline_data(stock_code, period, start_date, end_date)
|
||||||
df = self.data_manager.read_stock_data(stock_code, period, start_date, end_date)
|
|
||||||
|
|
||||||
if df.empty:
|
if df.empty:
|
||||||
logger.error("❌ 没有找到数据")
|
logger.error("❌ 没有找到数据")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
# 通过 StockDataTool 计算技术指标
|
||||||
|
indicators_data = {}
|
||||||
|
if show_ma or show_macd:
|
||||||
|
try:
|
||||||
|
indicators = self.data_tool.calculate_indicators(
|
||||||
|
stock_code, period, start_date, end_date, params
|
||||||
|
)
|
||||||
|
if indicators:
|
||||||
|
indicators_data = indicators
|
||||||
|
logger.info("✅ 技术指标计算完成")
|
||||||
|
else:
|
||||||
|
logger.warning("⚠️ 技术指标计算失败")
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"⚠️ 技术指标计算异常: {e}")
|
||||||
|
|
||||||
# 渲染图表
|
# 渲染图表
|
||||||
return self.chart_renderer.render_chart(df, stock_code, period, show_volume,
|
return self.chart_renderer.render_chart(
|
||||||
show_macd, show_ma, params, default_window=150)
|
df, stock_code, period, indicators_data,
|
||||||
|
show_volume, show_macd, show_ma, params, default_window=150
|
||||||
|
)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"❌ 显示K线图失败: {e}")
|
logger.error(f"❌ 显示K线图失败: {e}")
|
||||||
@ -434,13 +438,31 @@ class StockKlineViewer:
|
|||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
"""主函数 - 演示K线图查看器的使用"""
|
"""主函数 - 演示K线图查看器的使用,重构版本"""
|
||||||
print("📈 股票K线图查看器 - 重构版本")
|
print("📈 股票K线图查看器 - 重构版本 (使用 StockDataTool)")
|
||||||
print("=" * 50)
|
print("=" * 60)
|
||||||
|
|
||||||
|
# 检查依赖
|
||||||
|
if StockDataTool is None or get_stock_tool is None:
|
||||||
|
print("❌ StockDataTool 不可用,请检查模块导入")
|
||||||
|
return
|
||||||
|
|
||||||
# 创建K线查看器
|
# 创建K线查看器
|
||||||
viewer = StockKlineViewer()
|
viewer = StockKlineViewer()
|
||||||
|
|
||||||
|
# 检查数据工具是否可用
|
||||||
|
if viewer.data_tool is None:
|
||||||
|
print("❌ 数据工具初始化失败")
|
||||||
|
return
|
||||||
|
|
||||||
|
# 检查数据库连接
|
||||||
|
if not viewer.data_tool.is_connected():
|
||||||
|
print("❌ 数据库未连接")
|
||||||
|
return
|
||||||
|
|
||||||
|
print("✅ StockDataTool 已就绪")
|
||||||
|
print(f"📊 数据库连接状态: {viewer.data_tool.get_connection_info()}")
|
||||||
|
|
||||||
# 测试股票代码列表
|
# 测试股票代码列表
|
||||||
test_stocks = ['601658.SH', '601398.SH']
|
test_stocks = ['601658.SH', '601398.SH']
|
||||||
test_period = '60m'
|
test_period = '60m'
|
||||||
@ -471,6 +493,16 @@ def main():
|
|||||||
for stock_code in test_stocks:
|
for stock_code in test_stocks:
|
||||||
print(f"\n🔍 查看股票: {stock_code} ({test_period})")
|
print(f"\n🔍 查看股票: {stock_code} ({test_period})")
|
||||||
|
|
||||||
|
# 先获取价格信息摘要
|
||||||
|
try:
|
||||||
|
price_info = viewer.data_tool.get_price_info(stock_code, test_period)
|
||||||
|
if price_info:
|
||||||
|
print(f"💰 最新价格: {price_info['latest_price']:.4f}")
|
||||||
|
print(f"📈 涨跌幅: {price_info['change_pct']:.2f}%")
|
||||||
|
print(f"📊 数据范围: {price_info['date_range']}")
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"⚠️ 获取价格信息失败: {e}")
|
||||||
|
|
||||||
# 显示K线图
|
# 显示K线图
|
||||||
success = viewer.show_kline_chart(
|
success = viewer.show_kline_chart(
|
||||||
stock_code=stock_code,
|
stock_code=stock_code,
|
||||||
|
|||||||
@ -1,12 +1,18 @@
|
|||||||
"""
|
"""
|
||||||
股票K线数据模型
|
股票K线数据模型 - 纯粹的 ORM 模型定义
|
||||||
使用peewee ORM定义股票K线数据表结构
|
只负责数据模型的定义与约束,不包含数据库操作逻辑
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from peewee import DateTimeField, DecimalField, BigIntegerField
|
from peewee import DateTimeField, DecimalField, BigIntegerField
|
||||||
from database_config import BaseModel, get_database
|
from database_manager import BaseModel, get_database
|
||||||
|
|
||||||
|
# 导入公共配置
|
||||||
|
from common import (
|
||||||
|
normalize_stock_code, get_table_name, LOG_PREFIXES,
|
||||||
|
KLINE_COLUMNS, FIELD_LIMITS
|
||||||
|
)
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
from decimal import Decimal
|
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@ -14,35 +20,26 @@ logger = logging.getLogger(__name__)
|
|||||||
class StockKlineBase(BaseModel):
|
class StockKlineBase(BaseModel):
|
||||||
"""
|
"""
|
||||||
股票K线数据基础模型
|
股票K线数据基础模型
|
||||||
这是所有股票K线表的基础模型,定义了通用字段
|
遵循公共配置的字段命名约定和数据类型定义
|
||||||
"""
|
"""
|
||||||
# 时间戳字段 - 设置为主键确保唯一性
|
# 时间戳字段 - 使用公共配置的列名
|
||||||
timestamp = DateTimeField(primary_key=True, help_text="K线时间戳")
|
timestamp = DateTimeField(primary_key=True, help_text="K线时间戳")
|
||||||
|
|
||||||
# OHLCV数据 - 使用Decimal确保精度
|
# OHLCV数据 - 使用Decimal确保精度,遵循公共配置的字段名称
|
||||||
open_price = DecimalField(max_digits=10, decimal_places=3, help_text="开盘价")
|
open = DecimalField(max_digits=10, decimal_places=3, help_text="开盘价")
|
||||||
high_price = DecimalField(max_digits=10, decimal_places=3, help_text="最高价")
|
high = DecimalField(max_digits=10, decimal_places=3, help_text="最高价")
|
||||||
low_price = DecimalField(max_digits=10, decimal_places=3, help_text="最低价")
|
low = DecimalField(max_digits=10, decimal_places=3, help_text="最低价")
|
||||||
close_price = DecimalField(max_digits=10, decimal_places=3, help_text="收盘价")
|
close = DecimalField(max_digits=10, decimal_places=3, help_text="收盘价")
|
||||||
volume = BigIntegerField(help_text="成交量")
|
volume = BigIntegerField(help_text="成交量")
|
||||||
amount = DecimalField(max_digits=20, decimal_places=2, help_text="成交额")
|
amount = DecimalField(max_digits=20, decimal_places=2, help_text="成交额", null=True)
|
||||||
|
|
||||||
def create_stock_kline_model(stock_code: str, period: str = "1d"):
|
def create_stock_kline_model(stock_code: str, period: str = "1d"):
|
||||||
"""
|
"""
|
||||||
动态创建股票K线数据表模型
|
动态创建股票K线数据表模型
|
||||||
|
使用公共配置的标准化函数确保表名一致性
|
||||||
为每个股票代码和周期创建独立的数据表,表名格式严格规范化:
|
|
||||||
kline_{clean_stock_code}_{period}
|
|
||||||
|
|
||||||
表名转换规则:
|
|
||||||
- "601658.SH" + "1d" -> kline_601658_sh_1d
|
|
||||||
- "000001.SZ" + "5m" -> kline_000001_sz_5m
|
|
||||||
- "510310.SH" + "15m" -> kline_510310_sh_15m
|
|
||||||
|
|
||||||
注意:股票代码必须包含市场后缀(.SH/.SZ)以确保表名唯一性
|
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
stock_code (str): 股票代码,必须包含市场后缀,如 "601658.SH", "000001.SZ"
|
stock_code (str): 股票代码,如 "601658.SH", "000001.SZ"
|
||||||
period (str): 数据周期,如 "1m", "5m", "1d",默认为 "1d"
|
period (str): 数据周期,如 "1m", "5m", "1d",默认为 "1d"
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
@ -51,14 +48,15 @@ def create_stock_kline_model(stock_code: str, period: str = "1d"):
|
|||||||
Raises:
|
Raises:
|
||||||
ValueError: 当股票代码格式不正确时
|
ValueError: 当股票代码格式不正确时
|
||||||
"""
|
"""
|
||||||
# 验证股票代码格式
|
# 使用公共配置标准化股票代码
|
||||||
if not stock_code or '.' not in stock_code:
|
normalized_code = normalize_stock_code(stock_code)
|
||||||
raise ValueError(f"股票代码格式错误,必须包含市场后缀: {stock_code}")
|
|
||||||
|
|
||||||
# 清理股票代码和周期,生成合法的表名
|
# 使用公共配置生成表名
|
||||||
clean_code = stock_code.replace(".", "_").replace("/", "_").replace("-", "_").lower()
|
table_name = get_table_name(normalized_code, period)
|
||||||
|
|
||||||
|
# 生成类名
|
||||||
|
clean_code = normalized_code.lower().replace(".", "_")
|
||||||
clean_period = period.replace(".", "_").replace("/", "_").replace("-", "_").lower()
|
clean_period = period.replace(".", "_").replace("/", "_").replace("-", "_").lower()
|
||||||
table_name = f"kline_{clean_code}_{clean_period}"
|
|
||||||
class_name = f"StockKline_{clean_code}_{clean_period}"
|
class_name = f"StockKline_{clean_code}_{clean_period}"
|
||||||
|
|
||||||
# 动态创建模型类
|
# 动态创建模型类
|
||||||
@ -68,258 +66,18 @@ def create_stock_kline_model(stock_code: str, period: str = "1d"):
|
|||||||
'table_name': table_name,
|
'table_name': table_name,
|
||||||
'database': get_database()
|
'database': get_database()
|
||||||
}),
|
}),
|
||||||
'stock_code': stock_code, # 保存原始股票代码
|
'stock_code': normalized_code, # 保存标准化后的股票代码
|
||||||
|
'period': period, # 保存时间周期
|
||||||
})
|
})
|
||||||
|
|
||||||
logger.info(f"📊 创建股票K线模型: {class_name} -> {table_name}")
|
logger.info(f"{LOG_PREFIXES['DATABASE']} 创建股票K线模型: {class_name} -> {table_name}")
|
||||||
return model_class
|
return model_class
|
||||||
|
|
||||||
def create_tables_for_stocks(stock_codes: list, period: str = "1d"):
|
# 其他可能的模型类可以在这里定义
|
||||||
"""
|
# class StockInfo(BaseModel):
|
||||||
为股票代码列表创建对应的数据表
|
# """股票基本信息模型"""
|
||||||
|
# pass
|
||||||
Args:
|
#
|
||||||
stock_codes (list): 股票代码列表,如 ["601658.SH", "000001.SZ"]
|
# class TradingCalendar(BaseModel):
|
||||||
period (str): 数据周期,如 "1m", "5m", "1d",默认为 "1d"
|
# """交易日历模型"""
|
||||||
|
# pass
|
||||||
Returns:
|
|
||||||
dict: 股票代码到模型类的映射字典
|
|
||||||
"""
|
|
||||||
stock_models = {}
|
|
||||||
|
|
||||||
try:
|
|
||||||
for stock_code in stock_codes:
|
|
||||||
# 创建模型类
|
|
||||||
model_class = create_stock_kline_model(stock_code, period)
|
|
||||||
|
|
||||||
# 尝试创建数据表,如果失败则跳过
|
|
||||||
try:
|
|
||||||
model_class.create_table(safe=True) # safe=True 表示如果表已存在则跳过
|
|
||||||
logger.info(f"✅ 创建股票表成功: {stock_code} ({period})")
|
|
||||||
except Exception as table_error:
|
|
||||||
# 如果是表已存在相关的错误,仍然可以使用现有表
|
|
||||||
if "already exists" in str(table_error) or "Duplicate" in str(table_error):
|
|
||||||
logger.warning(f"⚠️ 表已存在,使用现有表: {stock_code} ({period})")
|
|
||||||
else:
|
|
||||||
logger.error(f"❌ 创建表失败: {stock_code} ({period}) - {table_error}")
|
|
||||||
continue
|
|
||||||
|
|
||||||
stock_models[stock_code] = model_class
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"❌ 创建股票表失败: {e}")
|
|
||||||
# 不再抛出异常,返回已成功创建的模型
|
|
||||||
|
|
||||||
return stock_models
|
|
||||||
|
|
||||||
def save_dataframe_to_mysql(df, stock_model, batch_size=1000):
|
|
||||||
"""
|
|
||||||
将pandas DataFrame保存到MySQL数据库中 - 优化版本
|
|
||||||
使用批量插入和增量更新策略,大幅提升插入速度
|
|
||||||
|
|
||||||
Args:
|
|
||||||
df (pd.DataFrame): 包含K线数据的DataFrame,需要有时间索引
|
|
||||||
stock_model: 股票K线数据模型类
|
|
||||||
batch_size (int): 批量插入的大小,默认1000条
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
int: 成功插入的记录数量
|
|
||||||
"""
|
|
||||||
if df.empty:
|
|
||||||
logger.warning("⚠️ DataFrame为空,跳过保存")
|
|
||||||
return 0
|
|
||||||
|
|
||||||
try:
|
|
||||||
# 策略1: 查询已存在的时间戳,只插入新数据 (增量插入)
|
|
||||||
existing_timestamps = set()
|
|
||||||
try:
|
|
||||||
# 查询数据库中已存在的时间范围
|
|
||||||
min_time = df.index.min()
|
|
||||||
max_time = df.index.max()
|
|
||||||
existing_records = stock_model.select(stock_model.timestamp).where(
|
|
||||||
(stock_model.timestamp >= min_time) &
|
|
||||||
(stock_model.timestamp <= max_time)
|
|
||||||
)
|
|
||||||
existing_timestamps = {record.timestamp for record in existing_records}
|
|
||||||
logger.info(f"📊 数据库中已有 {len(existing_timestamps)} 条记录在时间范围内")
|
|
||||||
except Exception as e:
|
|
||||||
logger.warning(f"⚠️ 查询已存在记录失败,将尝试全量插入: {e}")
|
|
||||||
|
|
||||||
# 过滤出需要插入的新数据
|
|
||||||
new_data = []
|
|
||||||
for timestamp, row in df.iterrows():
|
|
||||||
if timestamp not in existing_timestamps:
|
|
||||||
new_data.append({
|
|
||||||
'timestamp': timestamp,
|
|
||||||
'open_price': Decimal(str(row['open'])),
|
|
||||||
'high_price': Decimal(str(row['high'])),
|
|
||||||
'low_price': Decimal(str(row['low'])),
|
|
||||||
'close_price': Decimal(str(row['close'])),
|
|
||||||
'volume': int(row['volume']),
|
|
||||||
'amount': Decimal(str(row['amount'])) if 'amount' in row else Decimal('0')
|
|
||||||
})
|
|
||||||
|
|
||||||
if not new_data:
|
|
||||||
logger.info("ℹ️ 没有新数据需要插入")
|
|
||||||
return 0
|
|
||||||
|
|
||||||
logger.info(f"📥 准备插入 {len(new_data)} 条新记录")
|
|
||||||
|
|
||||||
# 策略2: 批量插入新记录
|
|
||||||
success_count = 0
|
|
||||||
total_batches = (len(new_data) + batch_size - 1) // batch_size
|
|
||||||
|
|
||||||
for i in range(0, len(new_data), batch_size):
|
|
||||||
batch = new_data[i:i + batch_size]
|
|
||||||
batch_num = i // batch_size + 1
|
|
||||||
|
|
||||||
try:
|
|
||||||
# peewee批量插入
|
|
||||||
with stock_model._meta.database.atomic():
|
|
||||||
stock_model.insert_many(batch).execute()
|
|
||||||
success_count += len(batch)
|
|
||||||
logger.info(f"✅ 批次 {batch_num}/{total_batches}: 插入 {len(batch)} 条记录")
|
|
||||||
except Exception as e:
|
|
||||||
# 如果批量插入失败,尝试逐条插入这个批次
|
|
||||||
logger.warning(f"⚠️ 批次 {batch_num} 批量插入失败,尝试逐条插入: {e}")
|
|
||||||
for record in batch:
|
|
||||||
try:
|
|
||||||
with stock_model._meta.database.atomic():
|
|
||||||
stock_model.insert(**record).execute()
|
|
||||||
success_count += 1
|
|
||||||
except Exception as single_error:
|
|
||||||
if "Duplicate entry" in str(single_error) or "PRIMARY" in str(single_error):
|
|
||||||
continue # 跳过重复记录
|
|
||||||
else:
|
|
||||||
logger.warning(f"⚠️ 单条插入失败 {record['timestamp']}: {single_error}")
|
|
||||||
|
|
||||||
total_records = len(df)
|
|
||||||
new_records = len(new_data)
|
|
||||||
skipped_records = total_records - new_records
|
|
||||||
|
|
||||||
logger.info(f"✅ 插入完成: 新增 {success_count}/{new_records} 条,跳过重复 {skipped_records} 条")
|
|
||||||
return success_count
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"❌ 保存K线数据到数据库失败: {e}")
|
|
||||||
raise
|
|
||||||
|
|
||||||
|
|
||||||
def save_dataframe_to_mysql_replace_mode(df, stock_model, batch_size=1000):
|
|
||||||
"""
|
|
||||||
替换模式保存 - 清空表后重新插入所有数据
|
|
||||||
适用于需要完整替换数据的场景
|
|
||||||
|
|
||||||
Args:
|
|
||||||
df (pd.DataFrame): 包含K线数据的DataFrame
|
|
||||||
stock_model: 股票K线数据模型类
|
|
||||||
batch_size (int): 批量插入的大小
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
int: 成功插入的记录数量
|
|
||||||
"""
|
|
||||||
if df.empty:
|
|
||||||
logger.warning("⚠️ DataFrame为空,跳过保存")
|
|
||||||
return 0
|
|
||||||
|
|
||||||
try:
|
|
||||||
# 清空表
|
|
||||||
clear_stock_table(stock_model)
|
|
||||||
|
|
||||||
# 准备所有数据
|
|
||||||
all_data = []
|
|
||||||
for timestamp, row in df.iterrows():
|
|
||||||
all_data.append({
|
|
||||||
'timestamp': timestamp,
|
|
||||||
'open_price': Decimal(str(row['open'])),
|
|
||||||
'high_price': Decimal(str(row['high'])),
|
|
||||||
'low_price': Decimal(str(row['low'])),
|
|
||||||
'close_price': Decimal(str(row['close'])),
|
|
||||||
'volume': int(row['volume']),
|
|
||||||
'amount': Decimal(str(row['amount'])) if 'amount' in row else Decimal('0')
|
|
||||||
})
|
|
||||||
|
|
||||||
# 批量插入
|
|
||||||
success_count = 0
|
|
||||||
total_batches = (len(all_data) + batch_size - 1) // batch_size
|
|
||||||
|
|
||||||
for i in range(0, len(all_data), batch_size):
|
|
||||||
batch = all_data[i:i + batch_size]
|
|
||||||
batch_num = i // batch_size + 1
|
|
||||||
|
|
||||||
try:
|
|
||||||
with stock_model._meta.database.atomic():
|
|
||||||
stock_model.insert_many(batch).execute()
|
|
||||||
success_count += len(batch)
|
|
||||||
logger.info(f"✅ 批次 {batch_num}/{total_batches}: 插入 {len(batch)} 条记录")
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"❌ 批次 {batch_num} 插入失败: {e}")
|
|
||||||
raise
|
|
||||||
|
|
||||||
logger.info(f"✅ 替换模式完成: 插入 {success_count}/{len(all_data)} 条记录")
|
|
||||||
return success_count
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"❌ 替换模式保存失败: {e}")
|
|
||||||
raise
|
|
||||||
|
|
||||||
|
|
||||||
def clear_all_tables_for_period(stock_codes, period):
|
|
||||||
"""
|
|
||||||
清空指定周期的所有股票表 - 维护工具函数
|
|
||||||
|
|
||||||
Args:
|
|
||||||
stock_codes (list): 股票代码列表
|
|
||||||
period (str): 数据周期
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
dict: 清空结果 {stock_code: deleted_count}
|
|
||||||
"""
|
|
||||||
results = {}
|
|
||||||
logger.info(f"🧹 开始清空 {period} 周期的所有股票表...")
|
|
||||||
|
|
||||||
for stock_code in stock_codes:
|
|
||||||
try:
|
|
||||||
model_class = create_stock_kline_model(stock_code, period)
|
|
||||||
deleted_count = clear_stock_table(model_class)
|
|
||||||
results[stock_code] = deleted_count
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"❌ 清空 {stock_code} ({period}) 表失败: {e}")
|
|
||||||
results[stock_code] = 0
|
|
||||||
|
|
||||||
total_deleted = sum(results.values())
|
|
||||||
logger.info(f"✅ 清空完成,共删除 {total_deleted} 条记录")
|
|
||||||
return results
|
|
||||||
|
|
||||||
def clear_stock_table(stock_model):
|
|
||||||
"""
|
|
||||||
清空股票K线数据表
|
|
||||||
|
|
||||||
Args:
|
|
||||||
stock_model: 股票K线数据模型类
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
int: 删除的记录数量
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
# 获取表名用于日志显示
|
|
||||||
table_name = stock_model._meta.table_name
|
|
||||||
|
|
||||||
# 先查询记录数量
|
|
||||||
count_before = stock_model.select().count()
|
|
||||||
|
|
||||||
if count_before > 0:
|
|
||||||
logger.info(f"🧹 正在清空表 {table_name},当前记录数: {count_before}")
|
|
||||||
|
|
||||||
# 删除所有记录
|
|
||||||
deleted_count = stock_model.delete().execute()
|
|
||||||
|
|
||||||
logger.info(f"✅ 成功清空表 {table_name},删除了 {deleted_count} 条记录")
|
|
||||||
return deleted_count
|
|
||||||
else:
|
|
||||||
logger.info(f"ℹ️ 表 {table_name} 已经是空的,无需清空")
|
|
||||||
return 0
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"❌ 清空表失败: {e}")
|
|
||||||
raise
|
|
||||||
|
|||||||
474
src/data_process_model/stockdata_manager.py
Normal file
474
src/data_process_model/stockdata_manager.py
Normal file
@ -0,0 +1,474 @@
|
|||||||
|
"""
|
||||||
|
股票数据管理器 - DataFrame ↔ 数据库转换层
|
||||||
|
负责将数据库中的数据转换为DataFrame格式,以及将DataFrame数据写入数据库
|
||||||
|
调用 database_manager.py 提供的底层功能
|
||||||
|
"""
|
||||||
|
|
||||||
|
import pandas as pd
|
||||||
|
import logging
|
||||||
|
from typing import Dict, List, Optional, Union, Any
|
||||||
|
from decimal import Decimal
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
|
# 导入底层依赖
|
||||||
|
from database_manager import get_database_manager
|
||||||
|
from stock_models import create_stock_kline_model, StockKlineBase
|
||||||
|
|
||||||
|
# 导入公共配置
|
||||||
|
from common import (
|
||||||
|
normalize_stock_code, get_table_name, get_cache_key,
|
||||||
|
validate_kline_data, LOG_PREFIXES, KLINE_COLUMNS, TimeFrame
|
||||||
|
)
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
class StockDataManager:
|
||||||
|
"""
|
||||||
|
股票数据管理器
|
||||||
|
|
||||||
|
职责:
|
||||||
|
1. 从数据库读取K线数据并转换为DataFrame
|
||||||
|
2. 将DataFrame格式的K线数据写入数据库
|
||||||
|
3. 提供数据查询、过滤、聚合等功能
|
||||||
|
4. 管理股票表的创建和维护
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
"""初始化股票数据管理器"""
|
||||||
|
self.db_manager = get_database_manager()
|
||||||
|
self.model_cache = {} # 缓存已创建的模型类
|
||||||
|
|
||||||
|
# 确保数据库连接
|
||||||
|
if not self.db_manager.is_connected():
|
||||||
|
self.db_manager.connect()
|
||||||
|
|
||||||
|
logger.info(f"{LOG_PREFIXES['SUCCESS']} 股票数据管理器初始化完成")
|
||||||
|
|
||||||
|
# ================================ 模型管理 ================================
|
||||||
|
|
||||||
|
def get_stock_model(self, stock_code: str, period: str = "1d"):
|
||||||
|
"""
|
||||||
|
获取或创建股票K线模型类
|
||||||
|
|
||||||
|
Args:
|
||||||
|
stock_code: 股票代码
|
||||||
|
period: 时间周期
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
股票K线模型类
|
||||||
|
"""
|
||||||
|
# 标准化股票代码
|
||||||
|
normalized_code = normalize_stock_code(stock_code)
|
||||||
|
model_key = f"{normalized_code}_{period}"
|
||||||
|
|
||||||
|
# 从缓存获取
|
||||||
|
if model_key in self.model_cache:
|
||||||
|
return self.model_cache[model_key]
|
||||||
|
|
||||||
|
# 创建新模型
|
||||||
|
model_class = create_stock_kline_model(normalized_code, period)
|
||||||
|
self.model_cache[model_key] = model_class
|
||||||
|
|
||||||
|
return model_class
|
||||||
|
|
||||||
|
def create_table(self, stock_code: str, period: str = "1d") -> bool:
|
||||||
|
"""
|
||||||
|
创建股票K线数据表
|
||||||
|
|
||||||
|
Args:
|
||||||
|
stock_code: 股票代码
|
||||||
|
period: 时间周期
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
bool: 创建成功返回True
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
model_class = self.get_stock_model(stock_code, period)
|
||||||
|
success = self.db_manager.create_table(model_class, safe=True)
|
||||||
|
|
||||||
|
if success:
|
||||||
|
table_name = get_table_name(normalize_stock_code(stock_code), period)
|
||||||
|
logger.info(f"{LOG_PREFIXES['SUCCESS']} 创建表成功: {table_name}")
|
||||||
|
|
||||||
|
return success
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"{LOG_PREFIXES['ERROR']} 创建表失败: {stock_code} ({period}) - {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
def create_tables_for_stocks(self, stock_codes: List[str], period: str = "1d") -> Dict[str, bool]:
|
||||||
|
"""
|
||||||
|
批量创建股票表
|
||||||
|
|
||||||
|
Args:
|
||||||
|
stock_codes: 股票代码列表
|
||||||
|
period: 时间周期
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Dict[str, bool]: 创建结果 {stock_code: success}
|
||||||
|
"""
|
||||||
|
results = {}
|
||||||
|
logger.info(f"{LOG_PREFIXES['DATABASE']} 开始批量创建 {len(stock_codes)} 个股票表...")
|
||||||
|
|
||||||
|
for stock_code in stock_codes:
|
||||||
|
results[stock_code] = self.create_table(stock_code, period)
|
||||||
|
|
||||||
|
success_count = sum(results.values())
|
||||||
|
logger.info(f"{LOG_PREFIXES['SUCCESS']} 批量创建完成: {success_count}/{len(stock_codes)} 个表创建成功")
|
||||||
|
|
||||||
|
return results
|
||||||
|
|
||||||
|
# ================================ 数据读取 ================================
|
||||||
|
|
||||||
|
def read_stock_data(self,
|
||||||
|
stock_code: str,
|
||||||
|
period: str = "1d",
|
||||||
|
start_date: Optional[datetime] = None,
|
||||||
|
end_date: Optional[datetime] = None,
|
||||||
|
limit: Optional[int] = None) -> pd.DataFrame:
|
||||||
|
"""
|
||||||
|
从数据库读取股票K线数据并转换为DataFrame
|
||||||
|
|
||||||
|
Args:
|
||||||
|
stock_code: 股票代码
|
||||||
|
period: 时间周期
|
||||||
|
start_date: 开始日期
|
||||||
|
end_date: 结束日期
|
||||||
|
limit: 限制返回记录数
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
pd.DataFrame: K线数据DataFrame,以timestamp为索引
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
# 获取模型类
|
||||||
|
model_class = self.get_stock_model(stock_code, period)
|
||||||
|
|
||||||
|
# 构建查询
|
||||||
|
query = model_class.select()
|
||||||
|
|
||||||
|
# 添加时间范围过滤
|
||||||
|
if start_date:
|
||||||
|
query = query.where(model_class.timestamp >= start_date)
|
||||||
|
if end_date:
|
||||||
|
query = query.where(model_class.timestamp <= end_date)
|
||||||
|
|
||||||
|
# 按时间排序
|
||||||
|
query = query.order_by(model_class.timestamp)
|
||||||
|
|
||||||
|
# 添加限制
|
||||||
|
if limit:
|
||||||
|
query = query.limit(limit)
|
||||||
|
|
||||||
|
# 执行查询
|
||||||
|
records = list(query)
|
||||||
|
|
||||||
|
if not records:
|
||||||
|
logger.warning(f"{LOG_PREFIXES['WARNING']} 未找到数据: {stock_code} ({period})")
|
||||||
|
return pd.DataFrame()
|
||||||
|
|
||||||
|
# 转换为DataFrame
|
||||||
|
data = []
|
||||||
|
for record in records:
|
||||||
|
data.append({
|
||||||
|
'timestamp': record.timestamp,
|
||||||
|
'open': float(record.open),
|
||||||
|
'high': float(record.high),
|
||||||
|
'low': float(record.low),
|
||||||
|
'close': float(record.close),
|
||||||
|
'volume': record.volume,
|
||||||
|
'amount': float(record.amount) if record.amount else 0.0
|
||||||
|
})
|
||||||
|
|
||||||
|
df = pd.DataFrame(data)
|
||||||
|
df.set_index('timestamp', inplace=True)
|
||||||
|
|
||||||
|
logger.info(f"{LOG_PREFIXES['SUCCESS']} 成功读取 {len(df)} 条K线数据: {stock_code} ({period})")
|
||||||
|
|
||||||
|
return df
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"{LOG_PREFIXES['ERROR']} 读取股票数据失败: {stock_code} ({period}) - {e}")
|
||||||
|
return pd.DataFrame()
|
||||||
|
|
||||||
|
def get_existing_timestamps(self, stock_code: str, period: str = "1d",
|
||||||
|
start_date: Optional[datetime] = None,
|
||||||
|
end_date: Optional[datetime] = None) -> set:
|
||||||
|
"""
|
||||||
|
获取数据库中已存在的时间戳集合
|
||||||
|
|
||||||
|
Args:
|
||||||
|
stock_code: 股票代码
|
||||||
|
period: 时间周期
|
||||||
|
start_date: 开始日期
|
||||||
|
end_date: 结束日期
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
set: 时间戳集合
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
model_class = self.get_stock_model(stock_code, period)
|
||||||
|
|
||||||
|
query = model_class.select(model_class.timestamp)
|
||||||
|
|
||||||
|
if start_date:
|
||||||
|
query = query.where(model_class.timestamp >= start_date)
|
||||||
|
if end_date:
|
||||||
|
query = query.where(model_class.timestamp <= end_date)
|
||||||
|
|
||||||
|
timestamps = {record.timestamp for record in query}
|
||||||
|
|
||||||
|
logger.debug(f"{LOG_PREFIXES['DATABASE']} 查询到 {len(timestamps)} 个已存在时间戳")
|
||||||
|
|
||||||
|
return timestamps
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"{LOG_PREFIXES['WARNING']} 查询已存在时间戳失败: {e}")
|
||||||
|
return set()
|
||||||
|
|
||||||
|
# ================================ 数据写入 ================================
|
||||||
|
|
||||||
|
def save_dataframe(self, df: pd.DataFrame, stock_code: str, period: str = "1d",
|
||||||
|
mode: str = "append", batch_size: int = 1000) -> int:
|
||||||
|
"""
|
||||||
|
将DataFrame保存到数据库
|
||||||
|
|
||||||
|
Args:
|
||||||
|
df: K线数据DataFrame
|
||||||
|
stock_code: 股票代码
|
||||||
|
period: 时间周期
|
||||||
|
mode: 保存模式 ("append" 增量追加, "replace" 替换模式)
|
||||||
|
batch_size: 批量大小
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
int: 成功插入的记录数
|
||||||
|
"""
|
||||||
|
# 数据验证
|
||||||
|
if not validate_kline_data(df):
|
||||||
|
logger.error(f"{LOG_PREFIXES['ERROR']} DataFrame数据验证失败")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
# 确保表存在
|
||||||
|
if not self.create_table(stock_code, period):
|
||||||
|
logger.error(f"{LOG_PREFIXES['ERROR']} 创建表失败,无法保存数据")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
# 获取模型类
|
||||||
|
model_class = self.get_stock_model(stock_code, period)
|
||||||
|
|
||||||
|
if mode == "replace":
|
||||||
|
return self._save_replace_mode(df, model_class, batch_size)
|
||||||
|
else:
|
||||||
|
return self._save_append_mode(df, model_class, batch_size)
|
||||||
|
|
||||||
|
def _save_append_mode(self, df: pd.DataFrame, model_class, batch_size: int) -> int:
|
||||||
|
"""增量追加模式保存"""
|
||||||
|
try:
|
||||||
|
# 查询已存在的时间戳
|
||||||
|
min_time = df.index.min()
|
||||||
|
max_time = df.index.max()
|
||||||
|
|
||||||
|
# 获取表名进行查询(通过模型实例获取)
|
||||||
|
instance = model_class()
|
||||||
|
existing_timestamps = self.get_existing_timestamps(
|
||||||
|
instance.stock_code, instance.period, min_time, max_time
|
||||||
|
)
|
||||||
|
|
||||||
|
# 过滤出新数据
|
||||||
|
new_data = []
|
||||||
|
for timestamp, row in df.iterrows():
|
||||||
|
# 确保timestamp是datetime类型
|
||||||
|
if isinstance(timestamp, pd.Timestamp):
|
||||||
|
timestamp = timestamp.to_pydatetime()
|
||||||
|
if timestamp not in existing_timestamps:
|
||||||
|
new_data.append(self._row_to_dict(timestamp, row))
|
||||||
|
|
||||||
|
if not new_data:
|
||||||
|
logger.info(f"{LOG_PREFIXES['INFO']} 没有新数据需要插入")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
# 批量插入
|
||||||
|
success_count = self.db_manager.batch_insert(model_class, new_data, batch_size)
|
||||||
|
|
||||||
|
total_records = len(df)
|
||||||
|
skipped_records = total_records - len(new_data)
|
||||||
|
|
||||||
|
logger.info(f"{LOG_PREFIXES['SUCCESS']} 增量保存完成: 新增 {success_count}/{len(new_data)} 条,跳过重复 {skipped_records} 条")
|
||||||
|
|
||||||
|
return success_count
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"{LOG_PREFIXES['ERROR']} 增量保存失败: {e}")
|
||||||
|
raise
|
||||||
|
|
||||||
|
def _save_replace_mode(self, df: pd.DataFrame, model_class, batch_size: int) -> int:
|
||||||
|
"""替换模式保存"""
|
||||||
|
try:
|
||||||
|
# 清空表
|
||||||
|
self.db_manager.clear_table(model_class)
|
||||||
|
|
||||||
|
# 准备所有数据
|
||||||
|
all_data = []
|
||||||
|
for timestamp, row in df.iterrows():
|
||||||
|
# 确保timestamp是datetime类型
|
||||||
|
if isinstance(timestamp, pd.Timestamp):
|
||||||
|
timestamp = timestamp.to_pydatetime()
|
||||||
|
all_data.append(self._row_to_dict(timestamp, row))
|
||||||
|
|
||||||
|
# 批量插入
|
||||||
|
success_count = self.db_manager.batch_insert(model_class, all_data, batch_size)
|
||||||
|
|
||||||
|
logger.info(f"{LOG_PREFIXES['SUCCESS']} 替换模式保存完成: 插入 {success_count}/{len(all_data)} 条记录")
|
||||||
|
|
||||||
|
return success_count
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"{LOG_PREFIXES['ERROR']} 替换模式保存失败: {e}")
|
||||||
|
raise
|
||||||
|
|
||||||
|
def _row_to_dict(self, timestamp, row: pd.Series) -> Dict[str, Any]:
|
||||||
|
"""将DataFrame行转换为字典"""
|
||||||
|
# 确保timestamp是datetime类型
|
||||||
|
if isinstance(timestamp, pd.Timestamp):
|
||||||
|
timestamp = timestamp.to_pydatetime()
|
||||||
|
|
||||||
|
return {
|
||||||
|
'timestamp': timestamp,
|
||||||
|
'open': Decimal(str(row['open'])),
|
||||||
|
'high': Decimal(str(row['high'])),
|
||||||
|
'low': Decimal(str(row['low'])),
|
||||||
|
'close': Decimal(str(row['close'])),
|
||||||
|
'volume': int(row['volume']),
|
||||||
|
'amount': Decimal(str(row['amount'])) if 'amount' in row and pd.notna(row['amount']) else Decimal('0')
|
||||||
|
}
|
||||||
|
|
||||||
|
# ================================ 数据查询和分析 ================================
|
||||||
|
|
||||||
|
def get_latest_data(self, stock_code: str, period: str = "1d", count: int = 1) -> pd.DataFrame:
|
||||||
|
"""获取最新的K线数据"""
|
||||||
|
try:
|
||||||
|
model_class = self.get_stock_model(stock_code, period)
|
||||||
|
|
||||||
|
records = list(
|
||||||
|
model_class.select()
|
||||||
|
.order_by(model_class.timestamp.desc())
|
||||||
|
.limit(count)
|
||||||
|
)
|
||||||
|
|
||||||
|
if not records:
|
||||||
|
return pd.DataFrame()
|
||||||
|
|
||||||
|
# 转换为DataFrame并按时间正序排列
|
||||||
|
data = []
|
||||||
|
for record in reversed(records): # 反转以获得正序
|
||||||
|
data.append({
|
||||||
|
'timestamp': record.timestamp,
|
||||||
|
'open': float(record.open),
|
||||||
|
'high': float(record.high),
|
||||||
|
'low': float(record.low),
|
||||||
|
'close': float(record.close),
|
||||||
|
'volume': record.volume,
|
||||||
|
'amount': float(record.amount) if record.amount else 0.0
|
||||||
|
})
|
||||||
|
|
||||||
|
df = pd.DataFrame(data)
|
||||||
|
df.set_index('timestamp', inplace=True)
|
||||||
|
|
||||||
|
return df
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"{LOG_PREFIXES['ERROR']} 获取最新数据失败: {e}")
|
||||||
|
return pd.DataFrame()
|
||||||
|
|
||||||
|
def get_data_range(self, stock_code: str, period: str = "1d") -> Dict[str, Any]:
|
||||||
|
"""获取数据的时间范围和统计信息"""
|
||||||
|
try:
|
||||||
|
model_class = self.get_stock_model(stock_code, period)
|
||||||
|
|
||||||
|
# 使用peewee的聚合函数获取时间范围
|
||||||
|
from peewee import fn
|
||||||
|
min_time_query = model_class.select(fn.MIN(model_class.timestamp)).scalar()
|
||||||
|
max_time_query = model_class.select(fn.MAX(model_class.timestamp)).scalar()
|
||||||
|
count = model_class.select().count()
|
||||||
|
|
||||||
|
# 获取表名
|
||||||
|
table_name = get_table_name(normalize_stock_code(stock_code), period)
|
||||||
|
|
||||||
|
return {
|
||||||
|
'stock_code': stock_code,
|
||||||
|
'period': period,
|
||||||
|
'start_date': min_time_query,
|
||||||
|
'end_date': max_time_query,
|
||||||
|
'record_count': count,
|
||||||
|
'table_name': table_name
|
||||||
|
}
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"{LOG_PREFIXES['ERROR']} 获取数据范围失败: {e}")
|
||||||
|
return {}
|
||||||
|
|
||||||
|
# ================================ 表维护 ================================
|
||||||
|
|
||||||
|
def clear_table(self, stock_code: str, period: str = "1d") -> int:
|
||||||
|
"""清空股票表数据"""
|
||||||
|
try:
|
||||||
|
model_class = self.get_stock_model(stock_code, period)
|
||||||
|
return self.db_manager.clear_table(model_class)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"{LOG_PREFIXES['ERROR']} 清空表失败: {e}")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
def drop_table(self, stock_code: str, period: str = "1d") -> bool:
|
||||||
|
"""删除股票表"""
|
||||||
|
try:
|
||||||
|
model_class = self.get_stock_model(stock_code, period)
|
||||||
|
success = self.db_manager.drop_table(model_class, safe=True)
|
||||||
|
|
||||||
|
# 从缓存中移除
|
||||||
|
model_key = f"{normalize_stock_code(stock_code)}_{period}"
|
||||||
|
if model_key in self.model_cache:
|
||||||
|
del self.model_cache[model_key]
|
||||||
|
|
||||||
|
return success
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"{LOG_PREFIXES['ERROR']} 删除表失败: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
def get_available_stocks(self) -> List[str]:
|
||||||
|
"""获取可用的股票代码列表"""
|
||||||
|
# TODO: 实现从数据库获取所有表名并解析股票代码
|
||||||
|
logger.warning(f"{LOG_PREFIXES['WARNING']} get_available_stocks() 方法待实现")
|
||||||
|
return []
|
||||||
|
|
||||||
|
def get_available_periods(self, stock_code: str) -> List[str]:
|
||||||
|
"""获取指定股票的可用时间周期"""
|
||||||
|
# TODO: 实现从数据库获取指定股票的所有时间周期
|
||||||
|
logger.warning(f"{LOG_PREFIXES['WARNING']} get_available_periods() 方法待实现")
|
||||||
|
return []
|
||||||
|
|
||||||
|
def close(self):
|
||||||
|
"""关闭数据管理器"""
|
||||||
|
self.db_manager.disconnect()
|
||||||
|
logger.info(f"{LOG_PREFIXES['DATABASE']} 股票数据管理器已关闭")
|
||||||
|
|
||||||
|
# ================================ 便捷函数 ================================
|
||||||
|
|
||||||
|
def get_stock_data_manager():
|
||||||
|
"""获取股票数据管理器实例"""
|
||||||
|
return StockDataManager()
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
# 测试股票数据管理器
|
||||||
|
print(f"{LOG_PREFIXES['DATABASE']} 测试股票数据管理器...")
|
||||||
|
|
||||||
|
manager = StockDataManager()
|
||||||
|
|
||||||
|
# 测试创建表
|
||||||
|
success = manager.create_table("000001.SZ", "1d")
|
||||||
|
print(f"{LOG_PREFIXES['SUCCESS'] if success else LOG_PREFIXES['ERROR']} 创建表测试: {'成功' if success else '失败'}")
|
||||||
|
|
||||||
|
# 测试数据范围查询
|
||||||
|
data_range = manager.get_data_range("000001.SZ", "1d")
|
||||||
|
if data_range:
|
||||||
|
print(f"{LOG_PREFIXES['SUCCESS']} 数据范围查询成功: {data_range}")
|
||||||
|
|
||||||
|
manager.close()
|
||||||
@ -10,6 +10,9 @@ from dataclasses import dataclass, field
|
|||||||
from stock_data_manager import StockDataManager
|
from stock_data_manager import StockDataManager
|
||||||
import logging
|
import logging
|
||||||
|
|
||||||
|
# 导入公共配置
|
||||||
|
from common import LOG_PREFIXES, validate_kline_data
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
@ -90,7 +93,10 @@ class TechnicalIndicators:
|
|||||||
params = IndicatorParams()
|
params = IndicatorParams()
|
||||||
|
|
||||||
df = self._get_dataframe(stock_code, period, start_time, end_time)
|
df = self._get_dataframe(stock_code, period, start_time, end_time)
|
||||||
if df.empty:
|
|
||||||
|
# 使用公共配置验证数据
|
||||||
|
if not validate_kline_data(df):
|
||||||
|
logger.warning(f"{LOG_PREFIXES['WARNING']} K线数据验证失败或为空: {stock_code}")
|
||||||
return {}
|
return {}
|
||||||
|
|
||||||
# 转换为numpy数组(TA-Lib要求)
|
# 转换为numpy数组(TA-Lib要求)
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user