feat: 新增K线图绘制功能模块
新增文件: - plot_kline.py: K线图绘制核心模块 - kline_examples.py: 使用示例和演示代码 - KLINE_README.md: 详细使用说明文档 核心功能: 从MySQL数据库读取股票OHLCV数据 绘制专业的蜡烛图K线(红涨绿跌) 显示成交量柱状图 支持多时间周期 (1m, 5m, 15m, 30m, 60m, 1d等) 中文字体支持和图表美化 高分辨率PNG图片保存 命令行和编程两种使用方式 完善的异常处理和用户提示 使用方法: - 编程方式: plot_kline_interactive(stock_code, period, start_date, end_date) - 命令行: python plot_kline.py 601658.SH 1d 20250501 20250721 - 示例演示: python kline_examples.py 现在可以根据stockcode, period, start_date, end_date参数从数据库绘制专业K线图!
This commit is contained in:
parent
b5ad009503
commit
f2ee378da0
211
src/data_process_model/KLINE_README.md
Normal file
211
src/data_process_model/KLINE_README.md
Normal file
@ -0,0 +1,211 @@
|
||||
# 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界面展示
|
||||
- 交易信号标注
|
||||
161
src/data_process_model/kline_examples.py
Normal file
161
src/data_process_model/kline_examples.py
Normal file
@ -0,0 +1,161 @@
|
||||
"""
|
||||
K线图绘制使用示例
|
||||
|
||||
演示如何使用 plot_kline.py 模块绘制股票K线图
|
||||
|
||||
使用方法:
|
||||
1. 直接运行此文件
|
||||
2. 修改参数后运行
|
||||
3. 在其他文件中导入使用
|
||||
"""
|
||||
|
||||
from plot_kline import plot_kline_interactive
|
||||
|
||||
def example_single_stock():
|
||||
"""单个股票K线图示例"""
|
||||
print("🎯 单个股票K线图示例")
|
||||
print("=" * 40)
|
||||
|
||||
# 参数设置
|
||||
stock_code = "601658.SH" # 邮储银行
|
||||
period = "1d" # 日线
|
||||
start_date = "20250501" # 开始日期
|
||||
end_date = "20250721" # 结束日期
|
||||
|
||||
# 绘制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线图示例"""
|
||||
print("\n🎯 多周期K线图示例")
|
||||
print("=" * 40)
|
||||
|
||||
stock_code = "510310.SH" # 沪深300ETF
|
||||
periods = ["1m", "5m", "15m", "30m", "1d"]
|
||||
start_date = "20250701"
|
||||
end_date = "20250721"
|
||||
|
||||
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线图示例"""
|
||||
print("\n🎯 多股票K线图示例")
|
||||
print("=" * 40)
|
||||
|
||||
stock_codes = ["601658.SH", "510310.SH", "601398.SH"]
|
||||
stock_names = ["邮储银行", "沪深300ETF", "工商银行"]
|
||||
period = "1d"
|
||||
start_date = "20250601"
|
||||
end_date = "20250721"
|
||||
|
||||
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():
|
||||
"""主函数 - 展示所有示例"""
|
||||
print("🚀 K线图绘制工具 - 使用示例")
|
||||
print("=" * 50)
|
||||
|
||||
try:
|
||||
# 1. 单个股票示例
|
||||
example_single_stock()
|
||||
|
||||
# 2. 多周期示例
|
||||
example_multiple_periods()
|
||||
|
||||
# 3. 多股票示例
|
||||
example_multiple_stocks()
|
||||
|
||||
print("\n🎉 所有示例执行完成!")
|
||||
print("📁 生成的图表保存在 'charts' 目录中")
|
||||
|
||||
# 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()
|
||||
332
src/data_process_model/plot_kline.py
Normal file
332
src/data_process_model/plot_kline.py
Normal file
@ -0,0 +1,332 @@
|
||||
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()
|
||||
Loading…
Reference in New Issue
Block a user