feat: 重新设计K线图查看器,基于数据库配置
新增文件:
- stock_kline_viewer.py: 重新设计的K线图查看器核心类
- test_kline_viewer.py: 数据库连接和数据读取功能测试
核心架构改进:
采用面向对象设计,使用StockKlineViewer类
完全基于database_config.py和stock_models.py进行数据库操作
直接从MySQL数据库读取OHLCV数据,无中间层
完善的异常处理和日志记录
支持数据库连接生命周期管理
主要功能:
connect_database(): 连接MySQL数据库
read_stock_data(): 从数据库读取股票K线数据
plot_kline_chart(): 绘制专业K线图
view_stock_kline(): 完整的查看流程
支持多时间周期 (1m, 5m, 15m, 30m, 60m, 1d)
测试功能:
test_database_connection(): 测试数据库连接
test_data_reading(): 测试数据读取
test_table_existence(): 测试数据表存在性
使用方法:
viewer = StockKlineViewer()
viewer.view_stock_kline('601658.SH', '1d', '20250501', '20250721')
这是第一步:完成数据库连接和数据读取功能
This commit is contained in:
parent
ae2e4c0ec9
commit
4558bd9e59
@ -1,211 +0,0 @@
|
|||||||
# K线图绘制模块
|
|
||||||
|
|
||||||
## 📋 功能概述
|
|
||||||
|
|
||||||
这个模块提供了从MySQL数据库读取股票数据并绘制专业K线图的功能。支持多种时间周期和多个股票的K线图绘制。
|
|
||||||
|
|
||||||
## 📁 文件结构
|
|
||||||
|
|
||||||
```
|
|
||||||
src/data_process_model/
|
|
||||||
├── plot_kline.py # K线图绘制核心模块
|
|
||||||
├── kline_examples.py # 使用示例和演示
|
|
||||||
└── KLINE_README.md # 本说明文档
|
|
||||||
```
|
|
||||||
|
|
||||||
## 🚀 快速开始
|
|
||||||
|
|
||||||
### 1. 基本使用
|
|
||||||
|
|
||||||
```python
|
|
||||||
from plot_kline import plot_kline_interactive
|
|
||||||
|
|
||||||
# 绘制单个股票的K线图
|
|
||||||
success = plot_kline_interactive(
|
|
||||||
stock_code="601658.SH", # 股票代码
|
|
||||||
period="1d", # 数据周期
|
|
||||||
start_date="20250501", # 开始日期
|
|
||||||
end_date="20250721", # 结束日期
|
|
||||||
save_chart=True # 是否保存图表
|
|
||||||
)
|
|
||||||
```
|
|
||||||
|
|
||||||
### 2. 命令行使用
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# 在 data_process_model 目录下运行
|
|
||||||
python plot_kline.py 601658.SH 1d 20250501 20250721
|
|
||||||
```
|
|
||||||
|
|
||||||
### 3. 运行示例
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# 运行所有示例
|
|
||||||
python kline_examples.py
|
|
||||||
```
|
|
||||||
|
|
||||||
## 📊 支持的数据周期
|
|
||||||
|
|
||||||
- **分钟级**: `1m`, `5m`, `15m`, `30m`, `60m`
|
|
||||||
- **日级**: `1d`
|
|
||||||
- **其他**: `1w`, `1mon`, `1q`, `1hy`, `1y`
|
|
||||||
|
|
||||||
## 📈 功能特性
|
|
||||||
|
|
||||||
### K线图特性
|
|
||||||
- ✅ **标准K线**:支持红涨绿跌的中国股市习惯
|
|
||||||
- ✅ **上下影线**:完整显示最高价和最低价
|
|
||||||
- ✅ **成交量柱**:下方显示对应的成交量信息
|
|
||||||
- ✅ **中文支持**:图表标题、轴标签支持中文显示
|
|
||||||
- ✅ **时间轴**:智能格式化时间显示
|
|
||||||
- ✅ **图表保存**:支持高分辨率PNG图片保存
|
|
||||||
|
|
||||||
### 数据处理特性
|
|
||||||
- ✅ **数据库读取**:直接从MySQL数据库读取历史数据
|
|
||||||
- ✅ **日期筛选**:支持指定时间范围的数据查询
|
|
||||||
- ✅ **异常处理**:完善的错误处理和用户提示
|
|
||||||
- ✅ **数据验证**:自动验证数据完整性和有效性
|
|
||||||
|
|
||||||
## 🛠️ 核心函数说明
|
|
||||||
|
|
||||||
### `read_stock_data_from_db()`
|
|
||||||
从数据库读取股票数据
|
|
||||||
|
|
||||||
```python
|
|
||||||
def read_stock_data_from_db(stock_code, period, start_date, end_date):
|
|
||||||
"""
|
|
||||||
Args:
|
|
||||||
stock_code (str): 股票代码,如 "601658.SH"
|
|
||||||
period (str): 数据周期,如 "1d"
|
|
||||||
start_date (str): 开始日期,格式 "YYYYMMDD"
|
|
||||||
end_date (str): 结束日期,格式 "YYYYMMDD"
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
pd.DataFrame: OHLCV数据DataFrame
|
|
||||||
"""
|
|
||||||
```
|
|
||||||
|
|
||||||
### `plot_kline_chart()`
|
|
||||||
绘制K线图
|
|
||||||
|
|
||||||
```python
|
|
||||||
def plot_kline_chart(df, stock_code, period, save_path=None, show_volume=True):
|
|
||||||
"""
|
|
||||||
Args:
|
|
||||||
df (pd.DataFrame): OHLCV数据
|
|
||||||
stock_code (str): 股票代码
|
|
||||||
period (str): 数据周期
|
|
||||||
save_path (str): 保存路径(可选)
|
|
||||||
show_volume (bool): 是否显示成交量
|
|
||||||
"""
|
|
||||||
```
|
|
||||||
|
|
||||||
### `plot_kline_interactive()`
|
|
||||||
交互式K线图绘制(推荐使用)
|
|
||||||
|
|
||||||
```python
|
|
||||||
def plot_kline_interactive(stock_code, period, start_date, end_date, save_chart=True):
|
|
||||||
"""
|
|
||||||
Args:
|
|
||||||
stock_code (str): 股票代码
|
|
||||||
period (str): 数据周期
|
|
||||||
start_date (str): 开始日期
|
|
||||||
end_date (str): 结束日期
|
|
||||||
save_chart (bool): 是否保存图表
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
bool: 成功返回True,失败返回False
|
|
||||||
"""
|
|
||||||
```
|
|
||||||
|
|
||||||
## 📖 使用示例
|
|
||||||
|
|
||||||
### 示例1:单个股票日线图
|
|
||||||
```python
|
|
||||||
from plot_kline import plot_kline_interactive
|
|
||||||
|
|
||||||
# 绘制邮储银行的日线图
|
|
||||||
plot_kline_interactive(
|
|
||||||
stock_code="601658.SH",
|
|
||||||
period="1d",
|
|
||||||
start_date="20250501",
|
|
||||||
end_date="20250721"
|
|
||||||
)
|
|
||||||
```
|
|
||||||
|
|
||||||
### 示例2:多周期对比
|
|
||||||
```python
|
|
||||||
periods = ["1m", "5m", "15m", "30m", "1d"]
|
|
||||||
for period in periods:
|
|
||||||
plot_kline_interactive("510310.SH", period, "20250701", "20250721")
|
|
||||||
```
|
|
||||||
|
|
||||||
### 示例3:多股票对比
|
|
||||||
```python
|
|
||||||
stocks = ["601658.SH", "510310.SH", "601398.SH"]
|
|
||||||
for stock in stocks:
|
|
||||||
plot_kline_interactive(stock, "1d", "20250501", "20250721")
|
|
||||||
```
|
|
||||||
|
|
||||||
## 🎨 图表样式
|
|
||||||
|
|
||||||
### K线颜色规则
|
|
||||||
- 🔴 **红色K线**:收盘价 >= 开盘价(上涨)
|
|
||||||
- 🟢 **绿色K线**:收盘价 < 开盘价(下跌)
|
|
||||||
|
|
||||||
### 图表布局
|
|
||||||
- **上部分**:K线主图(占3/4高度)
|
|
||||||
- **下部分**:成交量柱状图(占1/4高度)
|
|
||||||
- **标题**:显示股票代码和数据周期
|
|
||||||
- **轴标签**:价格(元)、成交量、时间
|
|
||||||
|
|
||||||
### 成交量格式
|
|
||||||
- 自动格式化为:万、亿等单位
|
|
||||||
- 颜色与对应K线一致
|
|
||||||
|
|
||||||
## 📁 输出文件
|
|
||||||
|
|
||||||
### 图片保存
|
|
||||||
- **目录**:`charts/`
|
|
||||||
- **格式**:PNG (300 DPI)
|
|
||||||
- **命名规则**:`{股票代码}_{周期}_{开始日期}_{结束日期}_{时间戳}.png`
|
|
||||||
- **示例**:`601658_SH_1d_20250501_20250721_20250722_143052.png`
|
|
||||||
|
|
||||||
## ⚠️ 注意事项
|
|
||||||
|
|
||||||
1. **数据库连接**:确保MySQL数据库连接正常
|
|
||||||
2. **数据表存在**:确保对应股票和周期的数据表已创建并有数据
|
|
||||||
3. **依赖库安装**:需要安装matplotlib、pandas等库
|
|
||||||
4. **中文字体**:如果中文显示有问题,请检查系统中文字体
|
|
||||||
5. **图片目录**:charts目录会自动创建
|
|
||||||
|
|
||||||
## 🐛 常见问题
|
|
||||||
|
|
||||||
### Q: 提示"未找到数据"怎么办?
|
|
||||||
A: 检查数据库中是否有对应股票和时间范围的数据,确保先运行了数据下载程序。
|
|
||||||
|
|
||||||
### Q: 中文乱码怎么解决?
|
|
||||||
A: 检查系统是否安装了SimHei或Microsoft YaHei字体。
|
|
||||||
|
|
||||||
### Q: 图表不显示怎么办?
|
|
||||||
A: 可能是显示后端问题,尝试先保存图片再查看。
|
|
||||||
|
|
||||||
### Q: 命令行参数格式是什么?
|
|
||||||
A: `python plot_kline.py <股票代码> <周期> <开始日期> <结束日期>`
|
|
||||||
|
|
||||||
## 🔧 依赖库
|
|
||||||
|
|
||||||
```
|
|
||||||
pandas>=1.3.0
|
|
||||||
matplotlib>=3.5.0
|
|
||||||
peewee>=3.14.0
|
|
||||||
```
|
|
||||||
|
|
||||||
## 🚀 扩展功能
|
|
||||||
|
|
||||||
可以基于此模块扩展的功能:
|
|
||||||
- 技术指标叠加(MA、BOLL、RSI等)
|
|
||||||
- 多股票同屏对比
|
|
||||||
- 实时数据更新
|
|
||||||
- Web界面展示
|
|
||||||
- 交易信号标注
|
|
||||||
@ -1,188 +0,0 @@
|
|||||||
"""
|
|
||||||
K线图绘制使用示例
|
|
||||||
|
|
||||||
演示如何使用 plot_kline.py 模块绘制股票K线图
|
|
||||||
配置与main.py保持一致,确保数据来源和参数统一
|
|
||||||
|
|
||||||
使用方法:
|
|
||||||
1. 直接运行此文件
|
|
||||||
2. 修改参数后运行
|
|
||||||
3. 在其他文件中导入使用
|
|
||||||
"""
|
|
||||||
|
|
||||||
from plot_kline import plot_kline_interactive
|
|
||||||
|
|
||||||
# 从main.py中导入相同的配置,保持一致性
|
|
||||||
g_stock_code_list = ["601658.SH", "510310.SH", "601398.SH"] # 与main.py相同
|
|
||||||
g_period_list = ["1m", "5m", "15m", "30m", "60m", "1d"] # 与main.py相同
|
|
||||||
g_start_date = "20250501" # 与main.py相同
|
|
||||||
g_end_date = "20250721" # 与main.py相同
|
|
||||||
|
|
||||||
def example_single_stock():
|
|
||||||
"""单个股票K线图示例 - 使用与main.py相同的配置"""
|
|
||||||
print("🎯 单个股票K线图示例")
|
|
||||||
print("=" * 40)
|
|
||||||
|
|
||||||
# 使用与main.py相同的配置参数
|
|
||||||
stock_code = g_stock_code_list[0] # 601658.SH 邮储银行
|
|
||||||
period = "1d" # 日线
|
|
||||||
start_date = g_start_date # 20250501
|
|
||||||
end_date = g_end_date # 20250721
|
|
||||||
|
|
||||||
print(f"📊 股票代码: {stock_code}")
|
|
||||||
print(f"📈 数据周期: {period}")
|
|
||||||
print(f"📅 时间范围: {start_date} ~ {end_date}")
|
|
||||||
|
|
||||||
# 绘制K线图
|
|
||||||
success = plot_kline_interactive(
|
|
||||||
stock_code=stock_code,
|
|
||||||
period=period,
|
|
||||||
start_date=start_date,
|
|
||||||
end_date=end_date,
|
|
||||||
save_chart=True
|
|
||||||
)
|
|
||||||
|
|
||||||
if success:
|
|
||||||
print("✅ K线图绘制成功!")
|
|
||||||
else:
|
|
||||||
print("❌ K线图绘制失败!")
|
|
||||||
|
|
||||||
|
|
||||||
def example_multiple_periods():
|
|
||||||
"""多周期K线图示例 - 使用与main.py相同的配置"""
|
|
||||||
print("\n🎯 多周期K线图示例")
|
|
||||||
print("=" * 40)
|
|
||||||
|
|
||||||
# 使用与main.py相同的配置
|
|
||||||
stock_code = g_stock_code_list[1] # 510310.SH 沪深300ETF
|
|
||||||
periods = g_period_list # 与main.py相同的周期列表
|
|
||||||
start_date = g_start_date # 20250501
|
|
||||||
end_date = g_end_date # 20250721
|
|
||||||
|
|
||||||
print(f"📊 股票代码: {stock_code}")
|
|
||||||
print(f"📈 数据周期: {', '.join(periods)}")
|
|
||||||
print(f"📅 时间范围: {start_date} ~ {end_date}")
|
|
||||||
|
|
||||||
for period in periods:
|
|
||||||
print(f"\n📈 绘制 {stock_code} 的 {period} 周期K线图...")
|
|
||||||
success = plot_kline_interactive(
|
|
||||||
stock_code=stock_code,
|
|
||||||
period=period,
|
|
||||||
start_date=start_date,
|
|
||||||
end_date=end_date,
|
|
||||||
save_chart=True
|
|
||||||
)
|
|
||||||
|
|
||||||
if success:
|
|
||||||
print(f"✅ {period} 周期K线图绘制成功")
|
|
||||||
else:
|
|
||||||
print(f"❌ {period} 周期K线图绘制失败")
|
|
||||||
|
|
||||||
|
|
||||||
def example_multiple_stocks():
|
|
||||||
"""多股票K线图示例 - 使用与main.py相同的配置"""
|
|
||||||
print("\n🎯 多股票K线图示例")
|
|
||||||
print("=" * 40)
|
|
||||||
|
|
||||||
# 使用与main.py相同的配置
|
|
||||||
stock_codes = g_stock_code_list # 与main.py相同的股票列表
|
|
||||||
stock_names = ["邮储银行", "沪深300ETF", "工商银行"]
|
|
||||||
period = "1d" # 日线
|
|
||||||
start_date = g_start_date # 20250501
|
|
||||||
end_date = g_end_date # 20250721
|
|
||||||
|
|
||||||
print(f"📊 股票代码: {', '.join(stock_codes)}")
|
|
||||||
print(f"📈 数据周期: {period}")
|
|
||||||
print(f"📅 时间范围: {start_date} ~ {end_date}")
|
|
||||||
|
|
||||||
for stock_code, stock_name in zip(stock_codes, stock_names):
|
|
||||||
print(f"\n📈 绘制 {stock_name}({stock_code}) 的K线图...")
|
|
||||||
success = plot_kline_interactive(
|
|
||||||
stock_code=stock_code,
|
|
||||||
period=period,
|
|
||||||
start_date=start_date,
|
|
||||||
end_date=end_date,
|
|
||||||
save_chart=True
|
|
||||||
)
|
|
||||||
|
|
||||||
if success:
|
|
||||||
print(f"✅ {stock_name} K线图绘制成功")
|
|
||||||
else:
|
|
||||||
print(f"❌ {stock_name} K线图绘制失败")
|
|
||||||
|
|
||||||
|
|
||||||
def interactive_mode():
|
|
||||||
"""交互式模式 - 用户输入参数"""
|
|
||||||
print("\n🎯 交互式K线图绘制")
|
|
||||||
print("=" * 40)
|
|
||||||
|
|
||||||
try:
|
|
||||||
# 获取用户输入
|
|
||||||
stock_code = input("请输入股票代码 (如 601658.SH): ").strip()
|
|
||||||
period = input("请输入数据周期 (如 1d): ").strip()
|
|
||||||
start_date = input("请输入开始日期 (如 20250501): ").strip()
|
|
||||||
end_date = input("请输入结束日期 (如 20250721): ").strip()
|
|
||||||
|
|
||||||
# 验证输入
|
|
||||||
if not all([stock_code, period, start_date, end_date]):
|
|
||||||
print("❌ 参数不能为空")
|
|
||||||
return
|
|
||||||
|
|
||||||
# 绘制K线图
|
|
||||||
print(f"\n📈 开始绘制 {stock_code} 的K线图...")
|
|
||||||
success = plot_kline_interactive(
|
|
||||||
stock_code=stock_code,
|
|
||||||
period=period,
|
|
||||||
start_date=start_date,
|
|
||||||
end_date=end_date,
|
|
||||||
save_chart=True
|
|
||||||
)
|
|
||||||
|
|
||||||
if success:
|
|
||||||
print("🎉 K线图绘制完成!")
|
|
||||||
else:
|
|
||||||
print("❌ K线图绘制失败!")
|
|
||||||
|
|
||||||
except KeyboardInterrupt:
|
|
||||||
print("\n⚠️ 用户取消操作")
|
|
||||||
except Exception as e:
|
|
||||||
print(f"❌ 发生错误: {e}")
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
|
||||||
"""主函数 - 展示所有示例,使用与main.py一致的配置"""
|
|
||||||
print("🚀 K线图绘制工具 - 使用示例")
|
|
||||||
print("=" * 50)
|
|
||||||
print("📋 配置信息 (与main.py一致):")
|
|
||||||
print(f"📊 股票代码: {', '.join(g_stock_code_list)}")
|
|
||||||
print(f"📈 数据周期: {', '.join(g_period_list)}")
|
|
||||||
print(f"📅 时间范围: {g_start_date} ~ {g_end_date}")
|
|
||||||
print("=" * 50)
|
|
||||||
|
|
||||||
try:
|
|
||||||
# 1. 单个股票示例
|
|
||||||
example_single_stock()
|
|
||||||
|
|
||||||
# 2. 多周期示例
|
|
||||||
example_multiple_periods()
|
|
||||||
|
|
||||||
# 3. 多股票示例
|
|
||||||
example_multiple_stocks()
|
|
||||||
|
|
||||||
print("\n🎉 所有示例执行完成!")
|
|
||||||
print("📁 生成的图表保存在 'charts' 目录中")
|
|
||||||
print("💡 提示: 这些配置与main.py保持完全一致")
|
|
||||||
|
|
||||||
# 4. 交互式模式(可选)
|
|
||||||
user_input = input("\n是否进入交互式模式?(y/n): ").strip().lower()
|
|
||||||
if user_input in ['y', 'yes']:
|
|
||||||
interactive_mode()
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
print(f"❌ 程序执行出错: {e}")
|
|
||||||
import traceback
|
|
||||||
traceback.print_exc()
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
||||||
416
src/data_process_model/stock_kline_viewer.py
Normal file
416
src/data_process_model/stock_kline_viewer.py
Normal file
@ -0,0 +1,416 @@
|
|||||||
|
"""
|
||||||
|
股票K线图查看器
|
||||||
|
从MySQL数据库读取股票K线数据并绘制专业K线图
|
||||||
|
|
||||||
|
主要功能:
|
||||||
|
1. 连接MySQL数据库
|
||||||
|
2. 读取股票OHLCV数据
|
||||||
|
3. 绘制专业K线图
|
||||||
|
4. 支持多时间周期查看
|
||||||
|
|
||||||
|
数据库配置来源: database_config.py
|
||||||
|
数据模型来源: stock_models.py
|
||||||
|
"""
|
||||||
|
|
||||||
|
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 os
|
||||||
|
|
||||||
|
# 导入数据库相关模块
|
||||||
|
from database_config import init_database, close_database, get_database
|
||||||
|
from stock_models import create_tables_for_stocks
|
||||||
|
|
||||||
|
# 配置日志
|
||||||
|
logging.basicConfig(level=logging.INFO)
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# 设置中文字体支持
|
||||||
|
plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei'] # 中文字体
|
||||||
|
plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题
|
||||||
|
|
||||||
|
|
||||||
|
class StockKlineViewer:
|
||||||
|
"""
|
||||||
|
股票K线图查看器类
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
"""
|
||||||
|
初始化K线图查看器
|
||||||
|
"""
|
||||||
|
self.db = None
|
||||||
|
self.is_connected = False
|
||||||
|
|
||||||
|
def connect_database(self):
|
||||||
|
"""
|
||||||
|
连接数据库
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
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
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"❌ 数据库连接异常: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
def disconnect_database(self):
|
||||||
|
"""
|
||||||
|
断开数据库连接
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
if self.is_connected:
|
||||||
|
close_database()
|
||||||
|
self.is_connected = False
|
||||||
|
logger.info("🔒 数据库连接已关闭")
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"❌ 关闭数据库连接异常: {e}")
|
||||||
|
|
||||||
|
def read_stock_data(self, 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
|
||||||
|
"""
|
||||||
|
if not self.is_connected:
|
||||||
|
logger.error("❌ 数据库未连接")
|
||||||
|
return pd.DataFrame()
|
||||||
|
|
||||||
|
try:
|
||||||
|
logger.info(f"📊 正在从数据库读取 {stock_code} 的 {period} 数据...")
|
||||||
|
|
||||||
|
# 获取对应的数据表模型
|
||||||
|
stock_models = create_tables_for_stocks([stock_code], period)
|
||||||
|
|
||||||
|
if stock_code not in stock_models:
|
||||||
|
logger.error(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") + timedelta(days=1) # 包含结束日期
|
||||||
|
|
||||||
|
# 查询数据
|
||||||
|
query = stock_model.select().where(
|
||||||
|
(stock_model.timestamp >= start_datetime) &
|
||||||
|
(stock_model.timestamp < end_datetime)
|
||||||
|
).order_by(stock_model.timestamp)
|
||||||
|
|
||||||
|
# 转换为DataFrame
|
||||||
|
data_list = []
|
||||||
|
for record in query:
|
||||||
|
data_list.append({
|
||||||
|
'time': 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),
|
||||||
|
'amount': float(record.amount)
|
||||||
|
})
|
||||||
|
|
||||||
|
df = pd.DataFrame(data_list)
|
||||||
|
|
||||||
|
if not df.empty:
|
||||||
|
df.set_index('time', inplace=True)
|
||||||
|
logger.info(f"✅ 成功读取 {len(df)} 条 {stock_code} 数据")
|
||||||
|
logger.info(f"📅 数据时间范围: {df.index.min()} ~ {df.index.max()}")
|
||||||
|
else:
|
||||||
|
logger.warning(f"⚠️ 未找到 {stock_code} 在指定时间范围内的数据")
|
||||||
|
|
||||||
|
return df
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"❌ 读取数据失败: {e}")
|
||||||
|
import traceback
|
||||||
|
traceback.print_exc()
|
||||||
|
return pd.DataFrame()
|
||||||
|
|
||||||
|
def plot_kline_chart(self, 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:
|
||||||
|
bool: 绘制成功返回True,失败返回False
|
||||||
|
"""
|
||||||
|
if df.empty:
|
||||||
|
logger.error("❌ 数据为空,无法绘制K线图")
|
||||||
|
return False
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 创建图表布局
|
||||||
|
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线图
|
||||||
|
self._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:
|
||||||
|
self._plot_volume(ax2, df)
|
||||||
|
ax2.set_ylabel('成交量', fontsize=12)
|
||||||
|
ax2.grid(True, alpha=0.3)
|
||||||
|
|
||||||
|
# 设置x轴时间格式
|
||||||
|
self._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')
|
||||||
|
logger.info(f"📈 K线图已保存到: {save_path}")
|
||||||
|
|
||||||
|
# 显示图表
|
||||||
|
plt.show()
|
||||||
|
logger.info("✅ K线图绘制完成")
|
||||||
|
return True
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"❌ 绘制K线图失败: {e}")
|
||||||
|
import traceback
|
||||||
|
traceback.print_exc()
|
||||||
|
return False
|
||||||
|
|
||||||
|
def _plot_candlestick(self, 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(self, 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(self._format_volume))
|
||||||
|
ax.set_xlim(-1, len(df))
|
||||||
|
|
||||||
|
def _format_volume(self, 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(self, 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 view_stock_kline(self, 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:
|
||||||
|
logger.info(f"🎯 正在为 {stock_code} 绘制 {period} 周期K线图...")
|
||||||
|
logger.info(f"📅 时间范围: {start_date} ~ {end_date}")
|
||||||
|
|
||||||
|
# 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)
|
||||||
|
|
||||||
|
if df.empty:
|
||||||
|
logger.error(f"❌ {stock_code} 在指定时间范围内没有数据")
|
||||||
|
return False
|
||||||
|
|
||||||
|
# 3. 生成保存路径(可选)
|
||||||
|
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)
|
||||||
|
|
||||||
|
# 4. 绘制K线图
|
||||||
|
success = self.plot_kline_chart(df, stock_code, period, save_path=save_path)
|
||||||
|
|
||||||
|
if success:
|
||||||
|
logger.info("🎉 K线图查看完成!")
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
logger.error("❌ K线图绘制失败")
|
||||||
|
return False
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"❌ 查看K线图异常: {e}")
|
||||||
|
import traceback
|
||||||
|
traceback.print_exc()
|
||||||
|
return False
|
||||||
|
finally:
|
||||||
|
# 5. 清理资源
|
||||||
|
self.disconnect_database()
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
"""
|
||||||
|
主函数 - 测试K线图查看器
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
# 创建K线图查看器
|
||||||
|
viewer = StockKlineViewer()
|
||||||
|
|
||||||
|
# 测试参数 - 与main.py保持一致
|
||||||
|
test_cases = [
|
||||||
|
{
|
||||||
|
"stock_code": "601658.SH",
|
||||||
|
"period": "1d",
|
||||||
|
"start_date": "20250501",
|
||||||
|
"end_date": "20250721"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"stock_code": "510310.SH",
|
||||||
|
"period": "1m",
|
||||||
|
"start_date": "20250701",
|
||||||
|
"end_date": "20250721"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|
||||||
|
print("🚀 股票K线图查看器测试")
|
||||||
|
print("=" * 50)
|
||||||
|
|
||||||
|
for i, test_case in enumerate(test_cases, 1):
|
||||||
|
print(f"\n📈 测试用例 {i}:")
|
||||||
|
print(f" 股票代码: {test_case['stock_code']}")
|
||||||
|
print(f" 数据周期: {test_case['period']}")
|
||||||
|
print(f" 时间范围: {test_case['start_date']} ~ {test_case['end_date']}")
|
||||||
|
|
||||||
|
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'],
|
||||||
|
save_chart=True
|
||||||
|
)
|
||||||
|
|
||||||
|
if success:
|
||||||
|
print(f"✅ 测试用例 {i} 成功")
|
||||||
|
else:
|
||||||
|
print(f"❌ 测试用例 {i} 失败")
|
||||||
|
|
||||||
|
print("\n🎉 测试完成!")
|
||||||
|
print("📁 生成的图表保存在 'charts' 目录中")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"❌ 程序执行出错: {e}")
|
||||||
|
import traceback
|
||||||
|
traceback.print_exc()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
158
src/data_process_model/test_kline_viewer.py
Normal file
158
src/data_process_model/test_kline_viewer.py
Normal file
@ -0,0 +1,158 @@
|
|||||||
|
"""
|
||||||
|
测试股票K线图查看器的数据库连接功能
|
||||||
|
|
||||||
|
主要测试:
|
||||||
|
1. 数据库连接功能
|
||||||
|
2. 数据读取功能
|
||||||
|
3. 基本的数据显示功能
|
||||||
|
"""
|
||||||
|
|
||||||
|
from stock_kline_viewer import StockKlineViewer
|
||||||
|
import logging
|
||||||
|
|
||||||
|
# 配置日志级别
|
||||||
|
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
def test_database_connection():
|
||||||
|
"""测试数据库连接功能"""
|
||||||
|
print("🔗 测试数据库连接功能")
|
||||||
|
print("=" * 40)
|
||||||
|
|
||||||
|
viewer = StockKlineViewer()
|
||||||
|
|
||||||
|
# 测试连接
|
||||||
|
success = viewer.connect_database()
|
||||||
|
|
||||||
|
if success:
|
||||||
|
print("✅ 数据库连接测试成功")
|
||||||
|
|
||||||
|
# 测试断开
|
||||||
|
viewer.disconnect_database()
|
||||||
|
print("✅ 数据库断开测试成功")
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
print("❌ 数据库连接测试失败")
|
||||||
|
return False
|
||||||
|
|
||||||
|
def test_data_reading():
|
||||||
|
"""测试数据读取功能"""
|
||||||
|
print("\n📊 测试数据读取功能")
|
||||||
|
print("=" * 40)
|
||||||
|
|
||||||
|
viewer = StockKlineViewer()
|
||||||
|
|
||||||
|
# 连接数据库
|
||||||
|
if not viewer.connect_database():
|
||||||
|
print("❌ 无法连接数据库,跳过数据读取测试")
|
||||||
|
return False
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 测试参数
|
||||||
|
stock_code = "601658.SH"
|
||||||
|
period = "1d"
|
||||||
|
start_date = "20250501"
|
||||||
|
end_date = "20250721"
|
||||||
|
|
||||||
|
print(f"📈 尝试读取 {stock_code} 的 {period} 数据...")
|
||||||
|
print(f"📅 时间范围: {start_date} ~ {end_date}")
|
||||||
|
|
||||||
|
# 读取数据
|
||||||
|
df = viewer.read_stock_data(stock_code, period, start_date, end_date)
|
||||||
|
|
||||||
|
if not df.empty:
|
||||||
|
print(f"✅ 数据读取成功!")
|
||||||
|
print(f"📊 数据行数: {len(df)}")
|
||||||
|
print(f"📋 数据列: {list(df.columns)}")
|
||||||
|
print(f"📅 时间范围: {df.index.min()} ~ {df.index.max()}")
|
||||||
|
print("🔍 数据预览:")
|
||||||
|
print(df.head(3))
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
print("⚠️ 读取到空数据")
|
||||||
|
return False
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"❌ 数据读取测试失败: {e}")
|
||||||
|
return False
|
||||||
|
finally:
|
||||||
|
viewer.disconnect_database()
|
||||||
|
|
||||||
|
def test_table_existence():
|
||||||
|
"""测试数据表是否存在"""
|
||||||
|
print("\n🗄️ 测试数据表存在性")
|
||||||
|
print("=" * 40)
|
||||||
|
|
||||||
|
viewer = StockKlineViewer()
|
||||||
|
|
||||||
|
if not viewer.connect_database():
|
||||||
|
print("❌ 无法连接数据库")
|
||||||
|
return False
|
||||||
|
|
||||||
|
try:
|
||||||
|
from stock_models import create_tables_for_stocks
|
||||||
|
|
||||||
|
# 测试创建数据表模型
|
||||||
|
stock_codes = ["601658.SH", "510310.SH", "601398.SH"]
|
||||||
|
periods = ["1d", "1m", "5m"]
|
||||||
|
|
||||||
|
for stock_code in stock_codes:
|
||||||
|
for period in periods:
|
||||||
|
try:
|
||||||
|
models = create_tables_for_stocks([stock_code], period)
|
||||||
|
if stock_code in models:
|
||||||
|
model = models[stock_code]
|
||||||
|
# 尝试查询一条记录来测试表是否存在
|
||||||
|
query = model.select().limit(1)
|
||||||
|
count = query.count()
|
||||||
|
print(f"✅ {stock_code}_{period} 表存在,记录数量: {count}")
|
||||||
|
else:
|
||||||
|
print(f"❌ {stock_code}_{period} 表模型创建失败")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"⚠️ {stock_code}_{period} 表可能不存在或无数据: {e}")
|
||||||
|
|
||||||
|
return True
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"❌ 表存在性测试失败: {e}")
|
||||||
|
return False
|
||||||
|
finally:
|
||||||
|
viewer.disconnect_database()
|
||||||
|
|
||||||
|
def main():
|
||||||
|
"""主测试函数"""
|
||||||
|
print("🧪 股票K线图查看器 - 数据库连接测试")
|
||||||
|
print("=" * 60)
|
||||||
|
|
||||||
|
# 1. 测试数据库连接
|
||||||
|
test1_passed = test_database_connection()
|
||||||
|
|
||||||
|
# 2. 测试数据表存在性
|
||||||
|
test2_passed = test_table_existence()
|
||||||
|
|
||||||
|
# 3. 测试数据读取
|
||||||
|
test3_passed = test_data_reading()
|
||||||
|
|
||||||
|
# 测试结果汇总
|
||||||
|
print("\n📋 测试结果汇总")
|
||||||
|
print("=" * 40)
|
||||||
|
print(f"🔗 数据库连接测试: {'✅ 通过' if test1_passed else '❌ 失败'}")
|
||||||
|
print(f"🗄️ 数据表存在测试: {'✅ 通过' if test2_passed else '❌ 失败'}")
|
||||||
|
print(f"📊 数据读取测试: {'✅ 通过' if test3_passed else '❌ 失败'}")
|
||||||
|
|
||||||
|
all_passed = test1_passed and test2_passed and test3_passed
|
||||||
|
|
||||||
|
if all_passed:
|
||||||
|
print("\n🎉 所有测试通过!K线图查看器数据库功能正常")
|
||||||
|
print("💡 提示: 现在可以使用 stock_kline_viewer.py 来查看K线图了")
|
||||||
|
else:
|
||||||
|
print("\n⚠️ 部分测试失败,请检查:")
|
||||||
|
if not test1_passed:
|
||||||
|
print(" - 数据库配置是否正确 (database_config.py)")
|
||||||
|
if not test2_passed:
|
||||||
|
print(" - 是否已运行 main.py 创建数据表并导入数据")
|
||||||
|
if not test3_passed:
|
||||||
|
print(" - 数据表中是否有对应时间范围的数据")
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
Loading…
Reference in New Issue
Block a user