feat: 重构K线查看器架构并修复股票代码标准化问题
主要更改: 1. 架构重构: - 分离StockDataManager(数据管理)和KlineChartRenderer(图表渲染) - 完全迁移到Peewee ORM,替换原有PyMySQL实现 - 实现模型缓存机制,提高查询性能 2. 股票代码标准化: - 新增_normalize_stock_code()方法,支持多种输入格式 - 自动识别市场:60xxx/51xxx/50xxx->SH, 00xxx/30xxx->SZ - 修复表名不匹配问题(kline_601658_1d -> kline_601658_sh_1d) 3. 代码清理: - 删除过时文件:macd_demo.py, plot_kline.py, test.py - 清理stock_models.py中的无用函数 - 保留main.py需要的核心功能 4. 数据库优化: - 添加get_database_connection()向后兼容函数 - 改进字段映射:open_price->open, high_price->high等 - 移除不必要的created_at/updated_at字段 5. 文档完善: - 新增STOCK_CODE_NORMALIZATION.md说明文档 - 更新函数注释和使用示例 修复问题: - 解决Table doesn't exist错误 - 统一股票代码格式规范 - 完善错误处理和日志记录
This commit is contained in:
parent
b202ca8b67
commit
0e2fa4a7b2
62
src/data_process_model/STOCK_CODE_NORMALIZATION.md
Normal file
62
src/data_process_model/STOCK_CODE_NORMALIZATION.md
Normal file
@ -0,0 +1,62 @@
|
||||
# 股票代码规范化说明
|
||||
|
||||
## 问题描述
|
||||
之前出现 "Table 'qtrade_stock_data.kline_601658_1d' doesn't exist" 错误,是因为:
|
||||
- 数据库中的表名:`kline_601658_sh_1d`(包含市场后缀)
|
||||
- 代码查询的表名:`kline_601658_1d`(缺少市场后缀)
|
||||
|
||||
## 解决方案
|
||||
|
||||
### 1. 股票代码标准化
|
||||
新增 `_normalize_stock_code()` 方法,支持多种输入格式:
|
||||
|
||||
```python
|
||||
# 输入格式 -> 标准格式
|
||||
"601658" -> "601658.SH" # 上海市场
|
||||
"000001" -> "000001.SZ" # 深圳市场
|
||||
"601658.SH" -> "601658.SH" # 已标准格式
|
||||
"000001.sz" -> "000001.SZ" # 大小写标准化
|
||||
```
|
||||
|
||||
### 2. 市场识别规则
|
||||
- **上海市场(.SH)**:60xxxx, 51xxxx, 50xxxx
|
||||
- **深圳市场(.SZ)**:00xxxx, 30xxxx
|
||||
- **默认**:未识别的代码默认为上海市场
|
||||
|
||||
### 3. 表名生成规范
|
||||
```
|
||||
股票代码 + 周期 -> 表名
|
||||
601658.SH + 1d -> kline_601658_sh_1d
|
||||
000001.SZ + 5m -> kline_000001_sz_5m
|
||||
510310.SH + 15m -> kline_510310_sh_15m
|
||||
```
|
||||
|
||||
### 4. 使用方式
|
||||
现在支持灵活的股票代码输入:
|
||||
|
||||
```python
|
||||
# 都可用,会自动标准化
|
||||
viewer.show_kline_chart("601658") # 短格式
|
||||
viewer.show_kline_chart("601658.SH") # 完整格式
|
||||
viewer.show_kline_chart("601658.sh") # 小写市场后缀
|
||||
```
|
||||
|
||||
## 主要修改
|
||||
|
||||
1. **StockDataManager**:
|
||||
- 新增 `_normalize_stock_code()` 方法
|
||||
- 修改 `_get_model_class()` 使用标准化代码
|
||||
- 更新文档说明支持的格式
|
||||
|
||||
2. **stock_models.py**:
|
||||
- 在 `create_stock_kline_model()` 中添加格式验证
|
||||
- 完善表名生成规则的文档说明
|
||||
|
||||
3. **测试数据**:
|
||||
- 更新测试股票代码为完整格式:`['601658.SH', '601398.SH', '510310.SH']`
|
||||
|
||||
## 效果
|
||||
- ✅ 解决表名不匹配问题
|
||||
- ✅ 支持多种股票代码输入格式
|
||||
- ✅ 确保表名生成的一致性和唯一性
|
||||
- ✅ 提供清晰的错误信息和验证
|
||||
@ -89,6 +89,37 @@ def get_database():
|
||||
"""
|
||||
return mysql_db
|
||||
|
||||
def get_database_connection():
|
||||
"""
|
||||
获取原始的MySQL数据库连接(用于K线查看器)
|
||||
|
||||
Returns:
|
||||
pymysql.Connection: PyMySQL数据库连接实例
|
||||
"""
|
||||
try:
|
||||
import pymysql
|
||||
|
||||
# 确保数据库已初始化
|
||||
if not mysql_db:
|
||||
init_database()
|
||||
|
||||
# 创建原始的pymysql连接
|
||||
connection = pymysql.connect(
|
||||
host=DATABASE_CONFIG['host'],
|
||||
port=DATABASE_CONFIG['port'],
|
||||
user=DATABASE_CONFIG['user'],
|
||||
password=DATABASE_CONFIG['password'],
|
||||
database=DATABASE_CONFIG['database'],
|
||||
charset=DATABASE_CONFIG['charset']
|
||||
)
|
||||
|
||||
logger.info("✅ 原始MySQL连接创建成功")
|
||||
return connection
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"❌ 创建原始MySQL连接失败: {e}")
|
||||
return None
|
||||
|
||||
# 基础模型类
|
||||
class BaseModel(Model):
|
||||
"""
|
||||
|
||||
@ -1,138 +0,0 @@
|
||||
"""
|
||||
MACD参数使用示例
|
||||
演示如何在K线图查看器中使用不同的MACD参数
|
||||
"""
|
||||
|
||||
from stock_kline_viewer import StockKlineViewer
|
||||
|
||||
def demo_macd_parameters():
|
||||
"""
|
||||
演示不同MACD参数的使用
|
||||
"""
|
||||
# 创建K线图查看器
|
||||
viewer = StockKlineViewer()
|
||||
|
||||
print("📊 MACD参数演示")
|
||||
print("=" * 60)
|
||||
|
||||
# 股票基本信息
|
||||
stock_code = "601658.SH" # 邮储银行
|
||||
period = "1d" # 日线
|
||||
start_date = "20250501"
|
||||
end_date = "20250721"
|
||||
|
||||
# 不同的MACD参数配置
|
||||
macd_configs = [
|
||||
{
|
||||
"name": "默认参数",
|
||||
"params": None, # 使用默认 (12,26,9)
|
||||
"description": "适合中长线分析,信号平稳"
|
||||
},
|
||||
{
|
||||
"name": "快速参数",
|
||||
"params": {
|
||||
"fast_period": 10, # 更快的快线
|
||||
"slow_period": 22, # 更快的慢线
|
||||
"signal_period": 7 # 更快的信号线
|
||||
},
|
||||
"description": "适合短线交易,信号更敏感"
|
||||
},
|
||||
{
|
||||
"name": "稳健参数",
|
||||
"params": {
|
||||
"fast_period": 14, # 更稳的快线
|
||||
"slow_period": 28, # 更稳的慢线
|
||||
"signal_period": 10 # 更稳的信号线
|
||||
},
|
||||
"description": "适合稳健策略,信号更平滑"
|
||||
}
|
||||
]
|
||||
|
||||
# 让用户选择要查看的配置
|
||||
print("请选择MACD参数配置:")
|
||||
for i, config in enumerate(macd_configs, 1):
|
||||
params_str = ""
|
||||
if config["params"]:
|
||||
p = config["params"]
|
||||
params_str = f"({p['fast_period']},{p['slow_period']},{p['signal_period']})"
|
||||
else:
|
||||
params_str = "(12,26,9)"
|
||||
|
||||
print(f" {i}. {config['name']} {params_str}")
|
||||
print(f" {config['description']}")
|
||||
|
||||
while True:
|
||||
try:
|
||||
choice = input("\n请输入选择的数字 (1-3): ").strip()
|
||||
choice_idx = int(choice) - 1
|
||||
|
||||
if 0 <= choice_idx < len(macd_configs):
|
||||
selected_config = macd_configs[choice_idx]
|
||||
break
|
||||
else:
|
||||
print("❌ 请输入1-3之间的数字")
|
||||
except ValueError:
|
||||
print("❌ 请输入有效的数字")
|
||||
|
||||
print(f"\n🎯 您选择了: {selected_config['name']}")
|
||||
print(f"📈 正在显示 {stock_code} 的K线图...")
|
||||
|
||||
# 显示K线图
|
||||
success = viewer.view_stock_kline(
|
||||
stock_code=stock_code,
|
||||
period=period,
|
||||
start_date=start_date,
|
||||
end_date=end_date,
|
||||
macd_params=selected_config["params"]
|
||||
)
|
||||
|
||||
if success:
|
||||
print("✅ 图表显示完成")
|
||||
else:
|
||||
print("❌ 图表显示失败")
|
||||
|
||||
def show_macd_parameter_guide():
|
||||
"""
|
||||
显示MACD参数调整指南
|
||||
"""
|
||||
print("\n📚 MACD参数调整指南")
|
||||
print("=" * 60)
|
||||
|
||||
print("🔧 参数说明:")
|
||||
print(" • fast_period (快速EMA周期):")
|
||||
print(" - 默认: 12")
|
||||
print(" - 范围: 5-15")
|
||||
print(" - 越小越敏感,信号越频繁")
|
||||
|
||||
print("\n • slow_period (慢速EMA周期):")
|
||||
print(" - 默认: 26")
|
||||
print(" - 范围: 20-30")
|
||||
print(" - 越大越平滑,滞后性越强")
|
||||
|
||||
print("\n • signal_period (信号线周期):")
|
||||
print(" - 默认: 9")
|
||||
print(" - 范围: 5-15")
|
||||
print(" - 影响买卖信号的敏感度")
|
||||
|
||||
print("\n💡 使用建议:")
|
||||
print(" 🔸 短线交易 (1-5天):")
|
||||
print(" - 推荐: (10,22,7) 或 (8,20,6)")
|
||||
print(" - 特点: 信号更敏感,适合快进快出")
|
||||
|
||||
print("\n 🔸 中线交易 (1-4周):")
|
||||
print(" - 推荐: (12,26,9) - 标准参数")
|
||||
print(" - 特点: 平衡敏感度和稳定性")
|
||||
|
||||
print("\n 🔸 长线投资 (1个月以上):")
|
||||
print(" - 推荐: (14,28,10) 或 (16,30,12)")
|
||||
print(" - 特点: 信号更稳定,减少假信号")
|
||||
|
||||
print("\n⚠️ 注意事项:")
|
||||
print(" • fast_period 必须小于 slow_period")
|
||||
print(" • 参数过小会产生过多噪音信号")
|
||||
print(" • 参数过大会导致信号过于滞后")
|
||||
print(" • 建议根据具体股票特性调整参数")
|
||||
|
||||
if __name__ == "__main__":
|
||||
show_macd_parameter_guide()
|
||||
demo_macd_parameters()
|
||||
@ -56,23 +56,6 @@ g_period_list = [
|
||||
g_fields = ["time", "open", "high", "low", "close", "volume", "amount"]
|
||||
|
||||
|
||||
def on_download_progress(data):
|
||||
"""
|
||||
数据下载进度回调函数
|
||||
|
||||
在xtdata下载数据过程中被调用,用于处理下载进度信息
|
||||
当前实现为空函数,可根据需要添加进度显示逻辑
|
||||
|
||||
Args:
|
||||
data (dict): 包含下载进度信息的字典
|
||||
|
||||
Returns:
|
||||
None: 无返回值
|
||||
"""
|
||||
# 静默处理,不打印进度信息
|
||||
pass
|
||||
|
||||
|
||||
def conv_time(ct):
|
||||
"""
|
||||
将时间戳转换为格式化时间字符串
|
||||
@ -195,7 +178,6 @@ def download_stock_data(stock_code, period, start_date, end_date):
|
||||
end_date,
|
||||
incrementally=True,
|
||||
)
|
||||
|
||||
history_data = xtdata.get_market_data_ex(
|
||||
g_fields,
|
||||
[stock_code],
|
||||
@ -203,7 +185,6 @@ def download_stock_data(stock_code, period, start_date, end_date):
|
||||
start_time=start_date,
|
||||
end_time=end_date,
|
||||
)
|
||||
|
||||
return history_data
|
||||
|
||||
|
||||
|
||||
@ -1,332 +0,0 @@
|
||||
import pandas as pd
|
||||
import matplotlib.pyplot as plt
|
||||
from matplotlib.patches import Rectangle
|
||||
from matplotlib.ticker import FuncFormatter
|
||||
from datetime import datetime
|
||||
import sys
|
||||
import os
|
||||
|
||||
# 导入数据库相关模块
|
||||
from database_config import init_database, close_database
|
||||
from stock_models import create_tables_for_stocks
|
||||
|
||||
# 设置中文字体支持
|
||||
plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei'] # 中文字体
|
||||
plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题
|
||||
|
||||
|
||||
def read_stock_data_from_db(stock_code, period, start_date, end_date):
|
||||
"""
|
||||
从数据库中读取股票K线数据
|
||||
|
||||
Args:
|
||||
stock_code (str): 股票代码,如 "601658.SH"
|
||||
period (str): 数据周期,如 "1m", "5m", "1d"
|
||||
start_date (str): 开始日期,格式 "YYYYMMDD"
|
||||
end_date (str): 结束日期,格式 "YYYYMMDD"
|
||||
|
||||
Returns:
|
||||
pd.DataFrame: 包含OHLCV数据的DataFrame,按时间排序
|
||||
列包括:time, open, high, low, close, volume, amount
|
||||
"""
|
||||
try:
|
||||
print(f"📊 正在从数据库读取 {stock_code} 的 {period} 数据...")
|
||||
|
||||
# 初始化数据库连接
|
||||
if not init_database():
|
||||
print("❌ 数据库连接失败")
|
||||
return pd.DataFrame()
|
||||
|
||||
# 获取对应的数据表模型
|
||||
stock_models = create_tables_for_stocks([stock_code], period)
|
||||
|
||||
if stock_code not in stock_models:
|
||||
print(f"❌ 未找到 {stock_code} 的数据表模型")
|
||||
return pd.DataFrame()
|
||||
|
||||
stock_model = stock_models[stock_code]
|
||||
|
||||
# 转换日期格式用于查询
|
||||
start_datetime = datetime.strptime(start_date, "%Y%m%d")
|
||||
end_datetime = datetime.strptime(end_date, "%Y%m%d")
|
||||
|
||||
# 查询数据
|
||||
query = stock_model.select().where(
|
||||
(stock_model.time >= start_datetime) &
|
||||
(stock_model.time <= end_datetime)
|
||||
).order_by(stock_model.time)
|
||||
|
||||
# 转换为DataFrame
|
||||
data_list = []
|
||||
for record in query:
|
||||
data_list.append({
|
||||
'time': record.time,
|
||||
'open': float(record.open),
|
||||
'high': float(record.high),
|
||||
'low': float(record.low),
|
||||
'close': float(record.close),
|
||||
'volume': int(record.volume),
|
||||
'amount': float(record.amount)
|
||||
})
|
||||
|
||||
df = pd.DataFrame(data_list)
|
||||
|
||||
if not df.empty:
|
||||
df.set_index('time', inplace=True)
|
||||
print(f"✅ 成功读取 {len(df)} 条 {stock_code} 数据")
|
||||
else:
|
||||
print(f"⚠️ 未找到 {stock_code} 在指定时间范围内的数据")
|
||||
|
||||
return df
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ 读取数据失败: {e}")
|
||||
return pd.DataFrame()
|
||||
finally:
|
||||
close_database()
|
||||
|
||||
|
||||
def plot_kline_chart(df, stock_code, period, save_path=None, show_volume=True):
|
||||
"""
|
||||
绘制K线图
|
||||
|
||||
Args:
|
||||
df (pd.DataFrame): 包含OHLCV数据的DataFrame
|
||||
stock_code (str): 股票代码
|
||||
period (str): 数据周期
|
||||
save_path (str, optional): 保存图片的路径,默认不保存
|
||||
show_volume (bool): 是否显示成交量,默认True
|
||||
|
||||
Returns:
|
||||
None: 显示图表
|
||||
"""
|
||||
if df.empty:
|
||||
print("❌ 数据为空,无法绘制K线图")
|
||||
return
|
||||
|
||||
# 创建图表布局
|
||||
if show_volume:
|
||||
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(15, 10),
|
||||
gridspec_kw={'height_ratios': [3, 1]},
|
||||
sharex=True)
|
||||
else:
|
||||
fig, ax1 = plt.subplots(1, 1, figsize=(15, 8))
|
||||
|
||||
# 绘制K线图
|
||||
plot_candlestick(ax1, df)
|
||||
|
||||
# 设置K线图标题和标签
|
||||
ax1.set_title(f'{stock_code} K线图 ({period}周期)', fontsize=16, fontweight='bold')
|
||||
ax1.set_ylabel('价格 (元)', fontsize=12)
|
||||
ax1.grid(True, alpha=0.3)
|
||||
|
||||
# 绘制成交量柱状图
|
||||
if show_volume:
|
||||
plot_volume(ax2, df)
|
||||
ax2.set_ylabel('成交量', fontsize=12)
|
||||
ax2.grid(True, alpha=0.3)
|
||||
|
||||
# 设置x轴时间格式
|
||||
setup_time_axis(ax2 if show_volume else ax1, df.index)
|
||||
|
||||
# 调整布局
|
||||
plt.tight_layout()
|
||||
|
||||
# 保存图片
|
||||
if save_path:
|
||||
plt.savefig(save_path, dpi=300, bbox_inches='tight')
|
||||
print(f"📈 K线图已保存到: {save_path}")
|
||||
|
||||
# 显示图表
|
||||
plt.show()
|
||||
|
||||
|
||||
def plot_candlestick(ax, df):
|
||||
"""
|
||||
绘制蜡烛图(K线)
|
||||
|
||||
Args:
|
||||
ax: matplotlib轴对象
|
||||
df: 包含OHLC数据的DataFrame
|
||||
"""
|
||||
# 计算K线颜色 (红涨绿跌)
|
||||
up_mask = df['close'] >= df['open']
|
||||
down_mask = df['close'] < df['open']
|
||||
|
||||
# 绘制上涨K线 (红色)
|
||||
for i, (time, row) in enumerate(df[up_mask].iterrows()):
|
||||
# K线实体
|
||||
height = row['close'] - row['open']
|
||||
ax.add_patch(Rectangle((i-0.3, row['open']), 0.6, height,
|
||||
facecolor='red', edgecolor='red', alpha=0.8))
|
||||
# 上影线
|
||||
ax.plot([i, i], [row['close'], row['high']], color='red', linewidth=1)
|
||||
# 下影线
|
||||
ax.plot([i, i], [row['open'], row['low']], color='red', linewidth=1)
|
||||
|
||||
# 绘制下跌K线 (绿色)
|
||||
for i, (time, row) in enumerate(df[down_mask].iterrows()):
|
||||
# K线实体
|
||||
height = row['open'] - row['close']
|
||||
ax.add_patch(Rectangle((i-0.3, row['close']), 0.6, height,
|
||||
facecolor='green', edgecolor='green', alpha=0.8))
|
||||
# 上影线
|
||||
ax.plot([i, i], [row['open'], row['high']], color='green', linewidth=1)
|
||||
# 下影线
|
||||
ax.plot([i, i], [row['close'], row['low']], color='green', linewidth=1)
|
||||
|
||||
# 设置x轴刻度
|
||||
ax.set_xlim(-1, len(df))
|
||||
ax.set_ylim(df[['low', 'high']].min().min() * 0.98,
|
||||
df[['low', 'high']].max().max() * 1.02)
|
||||
|
||||
|
||||
def plot_volume(ax, df):
|
||||
"""
|
||||
绘制成交量柱状图
|
||||
|
||||
Args:
|
||||
ax: matplotlib轴对象
|
||||
df: 包含成交量数据的DataFrame
|
||||
"""
|
||||
# 成交量颜色与K线一致
|
||||
colors = ['red' if close >= open_price else 'green'
|
||||
for close, open_price in zip(df['close'], df['open'])]
|
||||
|
||||
# 绘制成交量柱状图
|
||||
ax.bar(range(len(df)), df['volume'], color=colors, alpha=0.6)
|
||||
|
||||
# 格式化成交量显示
|
||||
ax.yaxis.set_major_formatter(FuncFormatter(format_volume))
|
||||
ax.set_xlim(-1, len(df))
|
||||
|
||||
|
||||
def format_volume(x, pos):
|
||||
"""
|
||||
格式化成交量显示(万、亿等)
|
||||
"""
|
||||
if x >= 100000000: # 亿
|
||||
return f'{x/100000000:.1f}亿'
|
||||
elif x >= 10000: # 万
|
||||
return f'{x/10000:.1f}万'
|
||||
else:
|
||||
return f'{int(x)}'
|
||||
|
||||
|
||||
def setup_time_axis(ax, time_index):
|
||||
"""
|
||||
设置时间轴格式
|
||||
|
||||
Args:
|
||||
ax: matplotlib轴对象
|
||||
time_index: 时间索引
|
||||
"""
|
||||
# 设置x轴标签为时间
|
||||
step = max(1, len(time_index) // 10) # 最多显示10个时间标签
|
||||
time_labels = [time_index[i].strftime('%m-%d %H:%M') if hasattr(time_index[i], 'strftime')
|
||||
else str(time_index[i]) for i in range(0, len(time_index), step)]
|
||||
tick_positions = list(range(0, len(time_index), step))
|
||||
|
||||
ax.set_xticks(tick_positions)
|
||||
ax.set_xticklabels(time_labels, rotation=45, ha='right')
|
||||
ax.set_xlabel('时间', fontsize=12)
|
||||
|
||||
|
||||
def main():
|
||||
"""
|
||||
主函数 - 用于测试K线图绘制功能
|
||||
"""
|
||||
try:
|
||||
# 测试参数
|
||||
stock_code = "601658.SH"
|
||||
period = "1d"
|
||||
start_date = "20250501"
|
||||
end_date = "20250721"
|
||||
|
||||
print("🎯 开始绘制K线图...")
|
||||
print("=" * 50)
|
||||
print(f"📊 股票代码: {stock_code}")
|
||||
print(f"📈 数据周期: {period}")
|
||||
print(f"📅 时间范围: {start_date} ~ {end_date}")
|
||||
print("=" * 50)
|
||||
|
||||
# 从数据库读取数据
|
||||
df = read_stock_data_from_db(stock_code, period, start_date, end_date)
|
||||
|
||||
if df.empty:
|
||||
print("❌ 未获取到数据,无法绘制K线图")
|
||||
return
|
||||
|
||||
# 生成保存路径
|
||||
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
save_filename = f"{stock_code.replace('.', '_')}_{period}_{start_date}_{end_date}_{timestamp}.png"
|
||||
save_path = os.path.join("charts", save_filename)
|
||||
|
||||
# 确保charts目录存在
|
||||
os.makedirs("charts", exist_ok=True)
|
||||
|
||||
# 绘制K线图
|
||||
plot_kline_chart(df, stock_code, period, save_path=save_path, show_volume=True)
|
||||
|
||||
print("🎉 K线图绘制完成!")
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ 程序执行出错: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
|
||||
|
||||
def plot_kline_interactive(stock_code, period, start_date, end_date, save_chart=True):
|
||||
"""
|
||||
交互式K线图绘制函数
|
||||
|
||||
Args:
|
||||
stock_code (str): 股票代码
|
||||
period (str): 数据周期
|
||||
start_date (str): 开始日期
|
||||
end_date (str): 结束日期
|
||||
save_chart (bool): 是否保存图表
|
||||
|
||||
Returns:
|
||||
bool: 成功返回True,失败返回False
|
||||
"""
|
||||
try:
|
||||
print(f"🎯 正在为 {stock_code} 绘制 {period} 周期K线图...")
|
||||
|
||||
# 从数据库读取数据
|
||||
df = read_stock_data_from_db(stock_code, period, start_date, end_date)
|
||||
|
||||
if df.empty:
|
||||
print(f"❌ {stock_code} 在指定时间范围内没有数据")
|
||||
return False
|
||||
|
||||
# 保存路径(可选)
|
||||
save_path = None
|
||||
if save_chart:
|
||||
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
save_filename = f"{stock_code.replace('.', '_')}_{period}_{start_date}_{end_date}_{timestamp}.png"
|
||||
save_path = os.path.join("charts", save_filename)
|
||||
os.makedirs("charts", exist_ok=True)
|
||||
|
||||
# 绘制K线图
|
||||
plot_kline_chart(df, stock_code, period, save_path=save_path)
|
||||
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ 绘制K线图失败: {e}")
|
||||
return False
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 支持命令行参数
|
||||
if len(sys.argv) > 4:
|
||||
stock_code = sys.argv[1]
|
||||
period = sys.argv[2]
|
||||
start_date = sys.argv[3]
|
||||
end_date = sys.argv[4]
|
||||
|
||||
plot_kline_interactive(stock_code, period, start_date, end_date)
|
||||
else:
|
||||
# 默认测试模式
|
||||
main()
|
||||
@ -1,50 +1,87 @@
|
||||
"""
|
||||
股票K线图查看器
|
||||
从MySQL数据库读取股票K线数据并绘制专业K线图
|
||||
|
||||
主要功能:
|
||||
1. 连接MySQL数据库
|
||||
2. 读取股票OHLCV数据
|
||||
3. 绘制专业K线图
|
||||
4. 支持多时间周期查看
|
||||
|
||||
数据库配置来源: database_config.py
|
||||
数据模型来源: stock_models.py
|
||||
股票K线图查看器 - 分离数据和显示功能
|
||||
支持从数据库加载股票数据并绘制交互式K线图,包含MACD指标
|
||||
"""
|
||||
|
||||
import pandas as pd
|
||||
import matplotlib.pyplot as plt
|
||||
from matplotlib.patches import Rectangle
|
||||
from matplotlib.ticker import FuncFormatter
|
||||
from datetime import datetime, timedelta
|
||||
import logging
|
||||
import sys
|
||||
import os
|
||||
import numpy as np
|
||||
from datetime import datetime, date
|
||||
|
||||
# 导入数据库相关模块
|
||||
from database_config import init_database, close_database, get_database
|
||||
# 添加路径以导入日志模块
|
||||
current_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
project_root = os.path.dirname(os.path.dirname(current_dir))
|
||||
sys.path.append(project_root)
|
||||
|
||||
# 配置日志
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
# 导入模块
|
||||
try:
|
||||
from src.log.logger import logger
|
||||
except ImportError:
|
||||
import logging
|
||||
logger = logging.getLogger(__name__)
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
|
||||
# 设置matplotlib为交互式模式,支持放大缩小和移动
|
||||
plt.ion() # 开启交互模式
|
||||
plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei'] # 中文字体
|
||||
plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题
|
||||
try:
|
||||
from database_config import init_database, get_database
|
||||
from stock_models import create_stock_kline_model
|
||||
except ImportError as e:
|
||||
logger.error(f"❌ 无法导入数据库配置模块: {e}")
|
||||
init_database = None
|
||||
get_database = None
|
||||
create_stock_kline_model = None
|
||||
|
||||
|
||||
class StockKlineViewer:
|
||||
class StockDataManager:
|
||||
"""
|
||||
股票K线图查看器类
|
||||
股票数据管理器 - 使用Peewee ORM
|
||||
专门负责数据的读取、处理和管理
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
"""
|
||||
初始化K线图查看器
|
||||
初始化数据管理器
|
||||
"""
|
||||
self.db = None
|
||||
self.database = None
|
||||
self.is_connected = False
|
||||
self.model_cache = {} # 缓存已创建的模型
|
||||
logger.info("📊 StockDataManager (Peewee) 初始化完成")
|
||||
|
||||
def _normalize_stock_code(self, stock_code):
|
||||
"""
|
||||
标准化股票代码格式
|
||||
|
||||
Args:
|
||||
stock_code (str): 股票代码,支持多种格式
|
||||
- "601658" -> "601658.SH"
|
||||
- "601658.SH" -> "601658.SH"
|
||||
- "000001" -> "000001.SZ"
|
||||
- "000001.SZ" -> "000001.SZ"
|
||||
- "510310" -> "510310.SH"
|
||||
|
||||
Returns:
|
||||
str: 标准化后的股票代码
|
||||
"""
|
||||
if not 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):
|
||||
"""
|
||||
@ -54,16 +91,17 @@ class StockKlineViewer:
|
||||
bool: 连接成功返回True,失败返回False
|
||||
"""
|
||||
try:
|
||||
logger.info("🔗 正在连接数据库...")
|
||||
success = init_database()
|
||||
if success:
|
||||
self.db = get_database()
|
||||
self.is_connected = True
|
||||
logger.info("✅ 数据库连接成功")
|
||||
return True
|
||||
else:
|
||||
logger.error("❌ 数据库连接失败")
|
||||
return False
|
||||
if not self.is_connected:
|
||||
# 初始化数据库
|
||||
if init_database():
|
||||
self.database = get_database()
|
||||
self.is_connected = True
|
||||
logger.info("✅ 数据库连接成功 (Peewee ORM)")
|
||||
return True
|
||||
else:
|
||||
logger.error("❌ 数据库初始化失败")
|
||||
return False
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"❌ 数据库连接异常: {e}")
|
||||
return False
|
||||
@ -73,143 +111,199 @@ class StockKlineViewer:
|
||||
断开数据库连接
|
||||
"""
|
||||
try:
|
||||
if self.is_connected:
|
||||
close_database()
|
||||
if self.database and self.is_connected:
|
||||
self.database.close()
|
||||
self.is_connected = False
|
||||
logger.info("🔒 数据库连接已关闭")
|
||||
logger.info("✅ 数据库连接已关闭 (Peewee)")
|
||||
except Exception as e:
|
||||
logger.error(f"❌ 关闭数据库连接异常: {e}")
|
||||
logger.error(f"❌ 关闭数据库连接时出错: {e}")
|
||||
|
||||
def read_stock_data(self, stock_code, period, start_date, end_date):
|
||||
def _get_model_class(self, stock_code, period):
|
||||
"""
|
||||
从数据库读取股票K线数据
|
||||
获取或创建股票K线模型类
|
||||
|
||||
Args:
|
||||
stock_code (str): 股票代码,如 "601658.SH"
|
||||
period (str): 数据周期,如 "1m", "5m", "1d"
|
||||
start_date (str): 开始日期,格式 "YYYYMMDD"
|
||||
end_date (str): 结束日期,格式 "YYYYMMDD"
|
||||
stock_code (str): 股票代码(支持短格式如'601658'或完整格式如'601658.SH')
|
||||
period (str): 数据周期
|
||||
|
||||
Returns:
|
||||
pd.DataFrame: 包含OHLCV数据的DataFrame,按时间排序
|
||||
列包括:time, open, high, low, close, volume, amount
|
||||
Model: Peewee模型类
|
||||
"""
|
||||
# 标准化股票代码
|
||||
normalized_code = self._normalize_stock_code(stock_code)
|
||||
model_key = f"{normalized_code}_{period}"
|
||||
|
||||
if model_key not in self.model_cache:
|
||||
try:
|
||||
# 创建模型类,使用标准化的股票代码
|
||||
model_class = create_stock_kline_model(normalized_code, period)
|
||||
self.model_cache[model_key] = model_class
|
||||
logger.info(f"📊 创建模型缓存: {model_key}")
|
||||
except Exception as e:
|
||||
logger.error(f"❌ 创建模型失败: {model_key} - {e}")
|
||||
return None
|
||||
|
||||
return self.model_cache[model_key]
|
||||
|
||||
def read_stock_data(self, stock_code, period='1d', start_date=None, end_date=None):
|
||||
"""
|
||||
从数据库读取股票K线数据 - 使用Peewee ORM
|
||||
|
||||
Args:
|
||||
stock_code (str): 股票代码,支持多种格式:
|
||||
- 短格式:'601658', '000001', '510310'
|
||||
- 完整格式:'601658.SH', '000001.SZ', '510310.SH'
|
||||
period (str): 数据周期,支持 1m, 5m, 15m, 30m, 60m, 1d
|
||||
start_date (str): 开始日期,格式 'YYYY-MM-DD',为None时获取最近数据
|
||||
end_date (str): 结束日期,格式 'YYYY-MM-DD',为None时获取到最新数据
|
||||
|
||||
Returns:
|
||||
pd.DataFrame: 包含OHLCV数据的DataFrame,索引为时间
|
||||
"""
|
||||
if not self.is_connected:
|
||||
logger.error("❌ 数据库未连接")
|
||||
return pd.DataFrame()
|
||||
|
||||
try:
|
||||
logger.info(f"📊 正在从数据库读取 {stock_code} 的 {period} 数据...")
|
||||
# 获取模型类
|
||||
model_class = self._get_model_class(stock_code, period)
|
||||
if not model_class:
|
||||
logger.error(f"❌ 无法获取模型类: {stock_code} ({period})")
|
||||
return pd.DataFrame()
|
||||
|
||||
# 生成表名(不创建表,只是获取表名)
|
||||
clean_code = stock_code.replace(".", "_").replace("/", "_").replace("-", "_").lower()
|
||||
clean_period = period.replace(".", "_").replace("/", "_").replace("-", "_").lower()
|
||||
table_name = f"kline_{clean_code}_{clean_period}"
|
||||
logger.info(f"📊 使用Peewee查询: {stock_code} ({period})")
|
||||
|
||||
# 转换日期格式用于查询
|
||||
start_datetime = datetime.strptime(start_date, "%Y%m%d")
|
||||
end_datetime = datetime.strptime(end_date, "%Y%m%d") + timedelta(days=1) # 包含结束日期
|
||||
# 构建查询
|
||||
query = model_class.select()
|
||||
|
||||
# 直接使用SQL查询,避免创建表
|
||||
sql = f"""
|
||||
SELECT timestamp, open_price, high_price, low_price, close_price, volume, amount
|
||||
FROM {table_name}
|
||||
WHERE timestamp >= %s AND timestamp < %s
|
||||
ORDER BY timestamp
|
||||
"""
|
||||
# 添加日期条件
|
||||
if start_date:
|
||||
from datetime import datetime
|
||||
start_datetime = datetime.strptime(start_date, '%Y-%m-%d')
|
||||
query = query.where(model_class.timestamp >= start_datetime)
|
||||
|
||||
cursor = self.db.execute_sql(sql, (start_datetime, end_datetime))
|
||||
results = cursor.fetchall()
|
||||
if end_date:
|
||||
from datetime import datetime
|
||||
end_datetime = datetime.strptime(end_date, '%Y-%m-%d')
|
||||
query = query.where(model_class.timestamp <= end_datetime)
|
||||
|
||||
# 转换为DataFrame
|
||||
data_list = []
|
||||
for record in results:
|
||||
data_list.append({
|
||||
'time': record[0], # timestamp
|
||||
'open': float(record[1]), # open_price
|
||||
'high': float(record[2]), # high_price
|
||||
'low': float(record[3]), # low_price
|
||||
'close': float(record[4]), # close_price
|
||||
'volume': int(record[5]), # volume
|
||||
'amount': float(record[6]) # amount
|
||||
# 按时间排序
|
||||
query = query.order_by(model_class.timestamp.asc())
|
||||
|
||||
# 如果没有指定日期范围,限制获取最近500条数据
|
||||
if not start_date and not end_date:
|
||||
query = query.limit(500)
|
||||
|
||||
logger.info(f"<EFBFBD> 执行Peewee查询: {stock_code} ({period})")
|
||||
|
||||
# 执行查询并转换为DataFrame
|
||||
results = []
|
||||
for record in query:
|
||||
results.append({
|
||||
'timestamp': record.timestamp,
|
||||
'open': float(record.open_price),
|
||||
'high': float(record.high_price),
|
||||
'low': float(record.low_price),
|
||||
'close': float(record.close_price),
|
||||
'volume': int(record.volume)
|
||||
})
|
||||
|
||||
df = pd.DataFrame(data_list)
|
||||
if not results:
|
||||
logger.warning(f"⚠️ 未找到数据: {stock_code} ({period})")
|
||||
return pd.DataFrame()
|
||||
|
||||
if not df.empty:
|
||||
df.set_index('time', inplace=True)
|
||||
# 转换为DataFrame
|
||||
df = pd.DataFrame(results)
|
||||
df['timestamp'] = pd.to_datetime(df['timestamp'])
|
||||
df.set_index('timestamp', inplace=True)
|
||||
|
||||
# 去除重复数据 - 保留第一条记录
|
||||
original_len = len(df)
|
||||
df = df[~df.index.duplicated(keep='first')]
|
||||
# 确保数据类型正确
|
||||
numeric_columns = ['open', 'high', 'low', 'close', 'volume']
|
||||
for col in numeric_columns:
|
||||
df[col] = pd.to_numeric(df[col], errors='coerce')
|
||||
|
||||
if len(df) < original_len:
|
||||
logger.info(f"🧹 检测到重复数据,已去重: {original_len} -> {len(df)} 条")
|
||||
|
||||
logger.info(f"✅ 成功读取 {len(df)} 条 {stock_code} 数据")
|
||||
logger.info(f"📅 数据时间范围: {df.index.min()} ~ {df.index.max()}")
|
||||
else:
|
||||
logger.warning(f"⚠️ 未找到 {stock_code} 在指定时间范围内的数据")
|
||||
logger.warning(f"💡 请确保表 {table_name} 存在且包含数据")
|
||||
logger.info(f"✅ 成功读取 {len(df)} 条数据 (Peewee ORM)")
|
||||
logger.info(f"📈 数据范围: {df.index.min()} 到 {df.index.max()}")
|
||||
|
||||
return df
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"❌ 读取数据失败: {e}")
|
||||
logger.error(f"💡 可能的原因: 表 {table_name} 不存在,请先运行 main.py 下载数据")
|
||||
logger.error(f"❌ 读取股票数据失败 (Peewee): {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return pd.DataFrame()
|
||||
|
||||
def plot_kline_chart(self, df, stock_code, period, show_volume=True, show_macd=True, macd_params=None):
|
||||
|
||||
class KlineChartRenderer:
|
||||
"""
|
||||
K线图表渲染器
|
||||
专门负责图表的绘制和显示
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
"""
|
||||
绘制可交互的K线图
|
||||
初始化图表渲染器
|
||||
"""
|
||||
# 设置中文字体
|
||||
plt.rcParams['font.sans-serif'] = ['SimHei'] # 显示中文
|
||||
plt.rcParams['axes.unicode_minus'] = False # 正常显示负号
|
||||
|
||||
# 图表配置
|
||||
self.figure_size = (15, 10)
|
||||
|
||||
logger.info("🎨 KlineChartRenderer 初始化完成")
|
||||
|
||||
def render_chart(self, df, stock_code, period, show_volume=True, show_macd=True, macd_params=None):
|
||||
"""
|
||||
渲染K线图表
|
||||
|
||||
Args:
|
||||
df (pd.DataFrame): 包含OHLCV数据的DataFrame
|
||||
df (pd.DataFrame): K线数据
|
||||
stock_code (str): 股票代码
|
||||
period (str): 数据周期
|
||||
show_volume (bool): 是否显示成交量,默认True
|
||||
show_macd (bool): 是否显示MACD指标,默认True
|
||||
macd_params (dict): MACD参数设置,格式如下:
|
||||
{
|
||||
'fast_period': 12, # 快速EMA周期
|
||||
'slow_period': 26, # 慢速EMA周期
|
||||
'signal_period': 9 # 信号线周期
|
||||
}
|
||||
show_volume (bool): 是否显示成交量
|
||||
show_macd (bool): 是否显示MACD指标
|
||||
macd_params (dict): MACD参数配置
|
||||
|
||||
Returns:
|
||||
bool: 绘制成功返回True,失败返回False
|
||||
bool: 渲染是否成功
|
||||
"""
|
||||
if df.empty:
|
||||
logger.error("❌ 数据为空,无法绘制K线图")
|
||||
return False
|
||||
|
||||
# 设置默认MACD参数
|
||||
if macd_params is None:
|
||||
macd_params = {
|
||||
'fast_period': 12,
|
||||
'slow_period': 26,
|
||||
'signal_period': 9
|
||||
}
|
||||
|
||||
try:
|
||||
# 创建新的figure窗口
|
||||
plt.figure(figsize=(16, 12))
|
||||
if df is None or df.empty:
|
||||
logger.error("❌ 没有数据可绘制")
|
||||
return False
|
||||
|
||||
# 创建图表布局
|
||||
if show_volume and show_macd:
|
||||
ax1 = plt.subplot(3, 1, 1) # K线图占上面50%
|
||||
ax2 = plt.subplot(3, 1, 2) # 成交量图占中间25%
|
||||
ax3 = plt.subplot(3, 1, 3) # MACD图占下面25%
|
||||
plt.subplots_adjust(hspace=0.4) # 调整子图间距
|
||||
elif show_volume:
|
||||
ax1 = plt.subplot(2, 1, 1) # K线图占上面3/4
|
||||
ax2 = plt.subplot(2, 1, 2) # 成交量图占下面1/4
|
||||
logger.info(f"🎨 开始绘制K线图 - {stock_code} ({period})")
|
||||
|
||||
# 设置默认MACD参数
|
||||
if macd_params is None:
|
||||
macd_params = {
|
||||
'fast_period': 12,
|
||||
'slow_period': 26,
|
||||
'signal_period': 9
|
||||
}
|
||||
|
||||
# 创建画布和子图
|
||||
plt.figure(figsize=self.figure_size)
|
||||
|
||||
# 计算子图数量和布局
|
||||
subplot_count = 1 # K线图
|
||||
if show_volume:
|
||||
subplot_count += 1
|
||||
if show_macd:
|
||||
subplot_count += 1
|
||||
|
||||
if subplot_count == 3: # K线+成交量+MACD
|
||||
ax1 = plt.subplot(3, 1, 1) # K线图
|
||||
ax2 = plt.subplot(3, 1, 2) # 成交量
|
||||
ax3 = plt.subplot(3, 1, 3) # MACD
|
||||
plt.subplots_adjust(hspace=0.3)
|
||||
elif show_macd:
|
||||
ax1 = plt.subplot(2, 1, 1) # K线图占上面3/4
|
||||
ax3 = plt.subplot(2, 1, 2) # MACD图占下面1/4
|
||||
elif subplot_count == 2: # K线 + (成交量 或 MACD)
|
||||
ax1 = plt.subplot(2, 1, 1) # K线图
|
||||
if show_volume:
|
||||
ax2 = plt.subplot(2, 1, 2) # 成交量
|
||||
else:
|
||||
ax3 = plt.subplot(2, 1, 2) # MACD
|
||||
plt.subplots_adjust(hspace=0.3)
|
||||
else:
|
||||
ax1 = plt.subplot(1, 1, 1)
|
||||
@ -463,137 +557,112 @@ class StockKlineViewer:
|
||||
ax.set_xticklabels(time_labels, rotation=45, ha='right')
|
||||
ax.set_xlabel('时间', fontsize=12)
|
||||
|
||||
def view_stock_kline(self, stock_code, period, start_date, end_date, macd_params=None):
|
||||
|
||||
class StockKlineViewer:
|
||||
"""
|
||||
股票K线图查看器 - 主控制器
|
||||
负责协调数据管理器和图表渲染器
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
"""
|
||||
查看股票K线图的完整流程
|
||||
初始化K线查看器
|
||||
"""
|
||||
self.data_manager = StockDataManager()
|
||||
self.chart_renderer = KlineChartRenderer()
|
||||
|
||||
logger.info("🚀 StockKlineViewer 初始化完成")
|
||||
|
||||
def show_kline_chart(self, stock_code, period='1d', start_date=None, end_date=None,
|
||||
show_volume=True, show_macd=True, macd_params=None):
|
||||
"""
|
||||
显示K线图表
|
||||
|
||||
Args:
|
||||
stock_code (str): 股票代码
|
||||
period (str): 数据周期
|
||||
start_date (str): 开始日期
|
||||
end_date (str): 结束日期
|
||||
macd_params (dict): MACD参数设置,格式如下:
|
||||
{
|
||||
'fast_period': 12, # 快速EMA周期
|
||||
'slow_period': 26, # 慢速EMA周期
|
||||
'signal_period': 9 # 信号线周期
|
||||
}
|
||||
show_volume (bool): 是否显示成交量
|
||||
show_macd (bool): 是否显示MACD指标
|
||||
macd_params (dict): MACD参数配置
|
||||
|
||||
Returns:
|
||||
bool: 成功返回True,失败返回False
|
||||
bool: 显示是否成功
|
||||
"""
|
||||
try:
|
||||
logger.info(f"🎯 正在为 {stock_code} 绘制 {period} 周期K线图...")
|
||||
logger.info(f"📅 时间范围: {start_date} ~ {end_date}")
|
||||
# 连接数据库
|
||||
if not self.data_manager.connect_database():
|
||||
return False
|
||||
|
||||
# 1. 连接数据库
|
||||
if not self.is_connected:
|
||||
if not self.connect_database():
|
||||
return False
|
||||
|
||||
# 2. 读取数据
|
||||
df = self.read_stock_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:
|
||||
logger.error(f"❌ {stock_code} 在指定时间范围内没有数据")
|
||||
logger.error("❌ 没有找到数据")
|
||||
return False
|
||||
|
||||
# 3. 绘制交互式K线图
|
||||
success = self.plot_kline_chart(df, stock_code, period, macd_params=macd_params)
|
||||
# 渲染图表
|
||||
success = self.chart_renderer.render_chart(df, stock_code, period, show_volume, show_macd, macd_params)
|
||||
|
||||
if success:
|
||||
logger.info("🎉 K线图查看完成!")
|
||||
return True
|
||||
else:
|
||||
logger.error("❌ K线图绘制失败")
|
||||
return False
|
||||
# 断开数据库连接
|
||||
self.data_manager.disconnect_database()
|
||||
|
||||
return success
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"❌ 查看K线图异常: {e}")
|
||||
logger.error(f"❌ 显示K线图失败: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
|
||||
# 确保数据库连接关闭
|
||||
self.data_manager.disconnect_database()
|
||||
return False
|
||||
finally:
|
||||
# 4. 清理资源
|
||||
self.disconnect_database()
|
||||
|
||||
|
||||
def main():
|
||||
"""
|
||||
主函数 - 测试K线图查看器(专注于日线数据)
|
||||
主函数 - 演示K线图查看器的使用
|
||||
"""
|
||||
try:
|
||||
# 创建K线图查看器
|
||||
viewer = StockKlineViewer()
|
||||
print("📈 股票K线图查看器")
|
||||
print("=" * 50)
|
||||
|
||||
# 测试参数 - 包含不同的MACD参数设置
|
||||
test_cases = [
|
||||
{
|
||||
"stock_code": "601658.SH", # 邮储银行
|
||||
"period": "1d",
|
||||
"start_date": "20250501",
|
||||
"end_date": "20250721",
|
||||
"macd_params": None, # 使用默认参数 (12,26,9)
|
||||
"description": "默认MACD参数"
|
||||
},
|
||||
# 可以添加更多测试用例来演示不同参数
|
||||
# {
|
||||
# "stock_code": "601658.SH",
|
||||
# "period": "1d",
|
||||
# "start_date": "20250501",
|
||||
# "end_date": "20250721",
|
||||
# "macd_params": {
|
||||
# "fast_period": 10, # 更敏感的快线
|
||||
# "slow_period": 22, # 更敏感的慢线
|
||||
# "signal_period": 7 # 更敏感的信号线
|
||||
# },
|
||||
# "description": "快速MACD参数 (10,22,7)"
|
||||
# }
|
||||
]
|
||||
# 创建K线查看器
|
||||
viewer = StockKlineViewer()
|
||||
|
||||
print("🚀 股票K线图查看器测试 - 日线数据")
|
||||
print("=" * 50)
|
||||
print("📊 MACD参数说明:")
|
||||
print(" fast_period: 快速EMA周期 (默认12, 范围5-15)")
|
||||
print(" slow_period: 慢速EMA周期 (默认26, 范围20-30)")
|
||||
print(" signal_period: 信号线周期 (默认9, 范围5-15)")
|
||||
print("=" * 50)
|
||||
# 测试股票代码列表 - 使用完整格式确保与数据库表名一致
|
||||
test_stocks = ['601658.SH', '601398.SH', '510310.SH']
|
||||
|
||||
for i, test_case in enumerate(test_cases, 1):
|
||||
print(f"\n📈 测试用例 {i}: {test_case['description']}")
|
||||
print(f" 股票代码: {test_case['stock_code']}")
|
||||
print(f" 数据周期: {test_case['period']}")
|
||||
print(f" 时间范围: {test_case['start_date']} ~ {test_case['end_date']}")
|
||||
for stock_code in test_stocks:
|
||||
print(f"\n🔍 查看股票: {stock_code}")
|
||||
|
||||
if test_case['macd_params']:
|
||||
params = test_case['macd_params']
|
||||
print(f" MACD参数: ({params['fast_period']},{params['slow_period']},{params['signal_period']})")
|
||||
else:
|
||||
print(f" MACD参数: (12,26,9) - 默认参数")
|
||||
# 配置MACD参数
|
||||
macd_config = {
|
||||
'fast_period': 12,
|
||||
'slow_period': 26,
|
||||
'signal_period': 9
|
||||
}
|
||||
|
||||
success = viewer.view_stock_kline(
|
||||
stock_code=test_case['stock_code'],
|
||||
period=test_case['period'],
|
||||
start_date=test_case['start_date'],
|
||||
end_date=test_case['end_date'],
|
||||
macd_params=test_case['macd_params']
|
||||
)
|
||||
# 显示K线图(包含成交量和MACD)
|
||||
success = viewer.show_kline_chart(
|
||||
stock_code=stock_code,
|
||||
period='1d',
|
||||
show_volume=True,
|
||||
show_macd=True,
|
||||
macd_params=macd_config
|
||||
)
|
||||
|
||||
if success:
|
||||
print(f"✅ 测试用例 {i} 成功")
|
||||
else:
|
||||
print(f"❌ 测试用例 {i} 失败")
|
||||
if success:
|
||||
print(f"✅ {stock_code} K线图显示完成")
|
||||
else:
|
||||
print(f"❌ {stock_code} K线图显示失败")
|
||||
|
||||
print("\n🎉 测试完成!")
|
||||
print("\n<EFBFBD> MACD参数调整建议:")
|
||||
print(" 🔸 短线交易: 使用(10,22,7)更敏感")
|
||||
print(" 🔸 中长线: 使用(12,26,9)标准参数")
|
||||
print(" 🔸 稳健策略: 使用(14,28,10)更平滑")
|
||||
# 询问是否继续
|
||||
user_input = input("\n继续查看下一个股票? (y/n, 默认y): ").strip().lower()
|
||||
if user_input == 'n':
|
||||
break
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"❌ 程序执行出错: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
print("\n👋 程序结束")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@ -27,24 +27,34 @@ class StockKlineBase(BaseModel):
|
||||
volume = BigIntegerField(help_text="成交量")
|
||||
amount = DecimalField(max_digits=20, decimal_places=2, help_text="成交额")
|
||||
|
||||
# 创建和更新时间
|
||||
created_at = DateTimeField(default=datetime.now, help_text="记录创建时间")
|
||||
updated_at = DateTimeField(default=datetime.now, help_text="记录更新时间")
|
||||
|
||||
def create_stock_kline_model(stock_code: str, period: str = "1d"):
|
||||
"""
|
||||
动态创建股票K线数据表模型
|
||||
|
||||
为每个股票代码和周期创建独立的数据表,表名格式: kline_{clean_stock_code}_{period}
|
||||
例如: 601658.SH, 1d -> kline_601658_sh_1d
|
||||
为每个股票代码和周期创建独立的数据表,表名格式严格规范化:
|
||||
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:
|
||||
stock_code (str): 股票代码,如 "601658.SH", "000001.SZ"
|
||||
stock_code (str): 股票代码,必须包含市场后缀,如 "601658.SH", "000001.SZ"
|
||||
period (str): 数据周期,如 "1m", "5m", "1d",默认为 "1d"
|
||||
|
||||
Returns:
|
||||
type: 动态创建的股票K线模型类
|
||||
|
||||
Raises:
|
||||
ValueError: 当股票代码格式不正确时
|
||||
"""
|
||||
# 验证股票代码格式
|
||||
if not stock_code or '.' not in stock_code:
|
||||
raise ValueError(f"股票代码格式错误,必须包含市场后缀: {stock_code}")
|
||||
|
||||
# 清理股票代码和周期,生成合法的表名
|
||||
clean_code = stock_code.replace(".", "_").replace("/", "_").replace("-", "_").lower()
|
||||
clean_period = period.replace(".", "_").replace("/", "_").replace("-", "_").lower()
|
||||
@ -151,39 +161,6 @@ def save_dataframe_to_mysql(df, stock_model, batch_size=1000):
|
||||
logger.error(f"❌ 保存K线数据到数据库失败: {e}")
|
||||
raise
|
||||
|
||||
def get_stock_kline_data(stock_model, start_time=None, end_time=None, limit=None):
|
||||
"""
|
||||
从数据库查询股票K线数据
|
||||
|
||||
Args:
|
||||
stock_model: 股票K线数据模型类
|
||||
start_time (datetime, optional): 开始时间
|
||||
end_time (datetime, optional): 结束时间
|
||||
limit (int, optional): 限制返回记录数
|
||||
|
||||
Returns:
|
||||
list: K线数据记录列表
|
||||
"""
|
||||
try:
|
||||
query = stock_model.select().order_by(stock_model.timestamp)
|
||||
|
||||
# 添加时间范围过滤
|
||||
if start_time:
|
||||
query = query.where(stock_model.timestamp >= start_time)
|
||||
if end_time:
|
||||
query = query.where(stock_model.timestamp <= end_time)
|
||||
if limit:
|
||||
query = query.limit(limit)
|
||||
|
||||
results = list(query)
|
||||
logger.info(f"📊 查询到 {len(results)} 条K线数据")
|
||||
return results
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"❌ 查询K线数据失败: {e}")
|
||||
raise
|
||||
|
||||
|
||||
def clear_stock_table(stock_model):
|
||||
"""
|
||||
清空股票K线数据表
|
||||
@ -216,36 +193,3 @@ def clear_stock_table(stock_model):
|
||||
except Exception as e:
|
||||
logger.error(f"❌ 清空表失败: {e}")
|
||||
raise
|
||||
|
||||
|
||||
def clear_all_stock_tables(stock_models):
|
||||
"""
|
||||
批量清空多个股票K线数据表
|
||||
|
||||
Args:
|
||||
stock_models (dict): 股票代码到模型的映射字典 {stock_code: model}
|
||||
|
||||
Returns:
|
||||
dict: 每个股票的删除记录数 {stock_code: deleted_count}
|
||||
"""
|
||||
results = {}
|
||||
|
||||
try:
|
||||
logger.info(f"🧹 开始批量清空 {len(stock_models)} 个股票表...")
|
||||
|
||||
for stock_code, stock_model in stock_models.items():
|
||||
try:
|
||||
deleted_count = clear_stock_table(stock_model)
|
||||
results[stock_code] = deleted_count
|
||||
except Exception as e:
|
||||
logger.error(f"❌ 清空 {stock_code} 表失败: {e}")
|
||||
results[stock_code] = 0
|
||||
|
||||
total_deleted = sum(results.values())
|
||||
logger.info(f"✅ 批量清空完成,总共删除 {total_deleted} 条记录")
|
||||
|
||||
return results
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"❌ 批量清空表失败: {e}")
|
||||
raise
|
||||
|
||||
Loading…
Reference in New Issue
Block a user