417 lines
14 KiB
Python
417 lines
14 KiB
Python
|
|
"""
|
|||
|
|
股票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()
|