223 lines
8.4 KiB
Python
223 lines
8.4 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""
|
||
K线图表组件
|
||
|
||
使用matplotlib绘制K线图,包含移动平均线和交叉信号标记
|
||
"""
|
||
|
||
import pandas as pd
|
||
import numpy as np
|
||
from datetime import datetime, timedelta
|
||
from typing import Optional, Tuple, List
|
||
|
||
from PySide6.QtWidgets import QWidget, QVBoxLayout, QMessageBox
|
||
import matplotlib.pyplot as plt
|
||
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
|
||
from matplotlib.figure import Figure
|
||
from matplotlib.patches import Rectangle
|
||
import matplotlib.dates as mdates
|
||
|
||
from analyzer.core.data_loader import DataLoader
|
||
from analyzer.core.indicators import MovingAverageIndicator
|
||
|
||
# 设置matplotlib中文字体
|
||
plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei', 'Arial']
|
||
plt.rcParams['axes.unicode_minus'] = False
|
||
|
||
class KlineChartWidget(QWidget):
|
||
"""K线图表组件"""
|
||
|
||
def __init__(self, parent=None):
|
||
super().__init__(parent)
|
||
self.data_loader = DataLoader()
|
||
self.ma_indicator = MovingAverageIndicator()
|
||
self.init_ui()
|
||
|
||
def init_ui(self):
|
||
"""初始化UI"""
|
||
layout = QVBoxLayout(self)
|
||
|
||
# 创建matplotlib图形
|
||
self.figure = Figure(figsize=(14, 8), dpi=100)
|
||
self.canvas = FigureCanvas(self.figure)
|
||
layout.addWidget(self.canvas)
|
||
|
||
# 设置样式
|
||
self.figure.patch.set_facecolor('white')
|
||
|
||
def plot_kline_data(self, stock_code: str, date_selected: datetime, timeframe: str) -> bool:
|
||
"""
|
||
绘制K线数据
|
||
|
||
Args:
|
||
stock_code: 股票代码
|
||
date_selected: 选择的日期
|
||
timeframe: 时间周期 ('15m', '30m', '60m')
|
||
|
||
Returns:
|
||
bool: 是否成功绘制
|
||
"""
|
||
try:
|
||
# 清空之前的图形
|
||
self.figure.clear()
|
||
|
||
# 获取数据
|
||
df = self.data_loader.load_kline_data(stock_code, date_selected, timeframe)
|
||
if df is None or df.empty:
|
||
self._show_no_data_message()
|
||
return False
|
||
|
||
# 计算移动平均线
|
||
df['ma5'] = self.ma_indicator.calculate_ma(df['close'], 5)
|
||
df['ma20'] = self.ma_indicator.calculate_ma(df['close'], 20)
|
||
|
||
# 保存当前数据框供时间轴设置使用
|
||
self._current_df = df
|
||
|
||
# 检测金叉死叉
|
||
golden_crosses, death_crosses = self.ma_indicator.find_crossovers(df['ma5'], df['ma20'])
|
||
|
||
# 绘制图形
|
||
ax = self.figure.add_subplot(111)
|
||
|
||
# 绘制K线
|
||
self._plot_candlesticks(ax, df)
|
||
|
||
# 绘制移动平均线
|
||
self._plot_moving_averages(ax, df)
|
||
|
||
# 标记金叉死叉
|
||
self._plot_crossover_signals(ax, df, golden_crosses, death_crosses)
|
||
|
||
# 设置图形样式
|
||
self._setup_chart_style(ax, stock_code, date_selected, timeframe)
|
||
|
||
# 刷新画布
|
||
self.canvas.draw()
|
||
|
||
return True
|
||
|
||
except Exception as e:
|
||
QMessageBox.critical(self, "绘图错误", f"绘制K线图时发生错误:\n{str(e)}")
|
||
return False
|
||
|
||
def _plot_candlesticks(self, ax, df: pd.DataFrame):
|
||
"""绘制K线"""
|
||
for i, (idx, row) in enumerate(df.iterrows()):
|
||
# 确定颜色:红涨绿跌
|
||
color = 'red' if row['close'] >= row['open'] else 'green'
|
||
|
||
# 绘制影线
|
||
ax.plot([i, i], [row['low'], row['high']], color='black', linewidth=0.8)
|
||
|
||
# 绘制实体
|
||
height = abs(row['close'] - row['open'])
|
||
bottom = min(row['open'], row['close'])
|
||
rect = Rectangle((i-0.4, bottom), 0.8, height,
|
||
facecolor=color, edgecolor='black', linewidth=0.5, alpha=0.8)
|
||
ax.add_patch(rect)
|
||
|
||
def _plot_moving_averages(self, ax, df: pd.DataFrame):
|
||
"""绘制移动平均线"""
|
||
x_positions = range(len(df))
|
||
|
||
# MA5线 - 过滤掉NaN值,确保线条连续
|
||
ma5_valid = df['ma5'].dropna()
|
||
if not ma5_valid.empty:
|
||
ma5_x = [i for i in x_positions if not pd.isna(df.iloc[i]['ma5'])]
|
||
ma5_y = [df.iloc[i]['ma5'] for i in ma5_x]
|
||
ax.plot(ma5_x, ma5_y, label='MA5', color='blue', linewidth=1.5, alpha=0.8)
|
||
|
||
# MA20线 - 过滤掉NaN值,确保线条连续
|
||
ma20_valid = df['ma20'].dropna()
|
||
if not ma20_valid.empty:
|
||
ma20_x = [i for i in x_positions if not pd.isna(df.iloc[i]['ma20'])]
|
||
ma20_y = [df.iloc[i]['ma20'] for i in ma20_x]
|
||
ax.plot(ma20_x, ma20_y, label='MA20', color='orange', linewidth=1.5, alpha=0.8)
|
||
|
||
def _plot_crossover_signals(self, ax, df: pd.DataFrame, golden_crosses: pd.Series, death_crosses: pd.Series):
|
||
"""标记金叉死叉信号"""
|
||
if not golden_crosses.empty:
|
||
# 金叉标记(向上箭头)
|
||
for idx in golden_crosses.index:
|
||
pos = df.index.get_loc(idx)
|
||
price = df.loc[idx, 'low'] * 0.995 # 在最低价下方一点
|
||
ax.annotate('↗', xy=(pos, price), fontsize=16, color='gold',
|
||
ha='center', va='top', weight='bold')
|
||
|
||
if not death_crosses.empty:
|
||
# 死叉标记(向下箭头)
|
||
for idx in death_crosses.index:
|
||
pos = df.index.get_loc(idx)
|
||
price = df.loc[idx, 'high'] * 1.005 # 在最高价上方一点
|
||
ax.annotate('↘', xy=(pos, price), fontsize=16, color='purple',
|
||
ha='center', va='bottom', weight='bold')
|
||
|
||
def _setup_chart_style(self, ax, stock_code: str, date_selected: datetime, timeframe: str):
|
||
"""设置图表样式"""
|
||
# 设置标题
|
||
timeframe_names = {'15m': '15分钟', '30m': '30分钟', '60m': '60分钟'}
|
||
title = f"{stock_code} K线图 - {date_selected.strftime('%Y-%m-%d')} ({timeframe_names.get(timeframe, timeframe)})"
|
||
ax.set_title(title, fontsize=14, pad=20)
|
||
|
||
# 设置坐标轴标签
|
||
ax.set_xlabel('时间', fontsize=12)
|
||
ax.set_ylabel('价格', fontsize=12)
|
||
|
||
# 设置X轴时间格式显示
|
||
self._setup_time_axis(ax)
|
||
|
||
# 设置网格
|
||
ax.grid(True, alpha=0.3)
|
||
|
||
# 设置图例
|
||
ax.legend(loc='upper left')
|
||
|
||
# 紧凑布局
|
||
self.figure.tight_layout()
|
||
|
||
def _setup_time_axis(self, ax):
|
||
"""设置时间轴格式"""
|
||
import matplotlib.dates as mdates
|
||
|
||
# 获取当前数据框
|
||
if hasattr(self, '_current_df') and self._current_df is not None:
|
||
df = self._current_df
|
||
|
||
# 设置X轴刻度位置和标签
|
||
num_ticks = min(len(df), 8) # 最多显示8个时间刻度
|
||
tick_positions = []
|
||
tick_labels = []
|
||
|
||
if num_ticks > 1:
|
||
step = len(df) // (num_ticks - 1)
|
||
for i in range(0, len(df), step):
|
||
if i < len(df):
|
||
tick_positions.append(i)
|
||
# 格式化时间为 HH:MM
|
||
time_str = df.iloc[i]['datetime'].strftime('%H:%M')
|
||
tick_labels.append(time_str)
|
||
|
||
# 确保最后一个点也被包含
|
||
if tick_positions[-1] != len(df) - 1:
|
||
tick_positions.append(len(df) - 1)
|
||
time_str = df.iloc[-1]['datetime'].strftime('%H:%M')
|
||
tick_labels.append(time_str)
|
||
|
||
ax.set_xticks(tick_positions)
|
||
ax.set_xticklabels(tick_labels, rotation=45, ha='right')
|
||
else:
|
||
# 如果没有数据,使用默认格式
|
||
ax.tick_params(axis='x', rotation=45)
|
||
|
||
def _show_no_data_message(self):
|
||
"""显示无数据消息"""
|
||
self.figure.clear()
|
||
ax = self.figure.add_subplot(111)
|
||
ax.text(0.5, 0.5, '该日期无数据\n\n请尝试选择其他交易日',
|
||
ha='center', va='center', fontsize=16,
|
||
bbox=dict(boxstyle="round,pad=1", facecolor="lightgray"))
|
||
ax.set_xlim(0, 1)
|
||
ax.set_ylim(0, 1)
|
||
ax.axis('off')
|
||
self.canvas.draw() |