数据库schema优化完成: 实现timestamp主键约束和重复数据防护

主要更新:
 优化数据库表结构
  - 将timestamp字段设置为主键,确保时间戳唯一性
  - 重新生成18个数据表(3股票6周期),应用新的主键约束
  - 成功插入51516条K线数据记录

 增强数据完整性
  - 修改save_dataframe_to_mysql函数使用insert()替代replace()
  - 添加重复键错误的静默处理,防止重复时间戳插入
  - 实现主键约束测试验证功能正常工作

 代码优化
  - 简化控制台输出,专注显示错误和关键信息
  - 保持CSV保存控制变量(g_save_csv=False)
  - 清理测试文件,移除过时的test_kline_viewer.py

 测试验证
  - 验证所有表结构正确应用timestamp主键约束
  - 测试重复时间戳防止功能正常工作(2条1条)
  - 确认数据质量和完整性

数据库现已具备高质量架构,支持可靠的量化交易数据分析。
This commit is contained in:
cuizhan 2025-07-22 22:42:43 +08:00
parent 4558bd9e59
commit f2e8e2fd95
4 changed files with 225 additions and 347 deletions

View File

@ -8,10 +8,16 @@ import time
from database_config import init_database, close_database from database_config import init_database, close_database
from stock_models import create_tables_for_stocks from stock_models import create_tables_for_stocks
# ============== 全局配置参数 ==============
g_stock_code_list = ["601658.SH", "510310.SH","601398.SH"] # 股票代码 g_stock_code_list = ["601658.SH", "510310.SH","601398.SH"] # 股票代码
g_start_date = "20250501" # 开始日期 g_start_date = "20250501" # 开始日期
g_end_date = "20250721" # 结束日期 g_end_date = "20250721" # 结束日期
# CSV文件保存控制变量
# 说明:设置为 True 启用CSV文件保存,False 则只保存到MySQL数据库
# 建议:日常使用设为 False 节省磁盘空间,需要分析时临时改为 True
g_save_csv = False # 默认不保存CSV文件,如需保存请设置为True
'''' ''''
"1m", # 1分钟 "1m", # 1分钟
@ -64,7 +70,7 @@ def on_download_progress(data):
Returns: Returns:
None: 无返回值 None: 无返回值
""" """
print(data) # 打印下载进度信息 # 静默处理,不打印进度信息
pass pass
@ -120,7 +126,6 @@ def save_dataframe_to_csv(df, stock_code, period, output_dir="data"):
""" """
try: try:
if df.empty: if df.empty:
print(f"⚠️ {stock_code} DataFrame为空,跳过保存")
return None return None
# 生成CSV文件名,添加微秒以避免重复 # 生成CSV文件名,添加微秒以避免重复
@ -130,27 +135,12 @@ def save_dataframe_to_csv(df, stock_code, period, output_dir="data"):
csv_filename = f"{clean_stock_code}_{period}_{timestamp}.csv" csv_filename = f"{clean_stock_code}_{period}_{timestamp}.csv"
csv_path = os.path.join(output_dir, csv_filename) csv_path = os.path.join(output_dir, csv_filename)
print(f"💾 准备保存 {stock_code} 到文件: {csv_filename}")
# 确保输出目录存在 # 确保输出目录存在
os.makedirs(output_dir, exist_ok=True) os.makedirs(output_dir, exist_ok=True)
# 保存为CSV # 保存为CSV
df.to_csv(csv_path, encoding="utf-8-sig") df.to_csv(csv_path, encoding="utf-8-sig")
# 打印保存信息
print(f"✅ {stock_code} 数据已保存到: {csv_path}")
print(f"📊 {stock_code} 数据形状: {df.shape}")
# 如果有时间索引,显示时间范围
if isinstance(df.index, pd.DatetimeIndex):
print(f"📅 {stock_code} 时间范围: {df.index.min()} 到 {df.index.max()}")
# 显示数据的基本统计信息
if not df.empty:
print(f"📈 {stock_code} 数据预览:")
print(df.head(3))
return csv_path return csv_path
except Exception as e: except Exception as e:
@ -199,7 +189,6 @@ def download_stock_data(stock_code, period, start_date, end_date):
>>> if data and "601658.SH" in data: >>> if data and "601658.SH" in data:
>>> print(f"601658.SH: {len(data['601658.SH']['time'])} 条数据") >>> print(f"601658.SH: {len(data['601658.SH']['time'])} 条数据")
""" """
print("🔄 正在下载历史数据...")
xtdata.download_history_data( xtdata.download_history_data(
stock_code, stock_code,
period, period,
@ -208,7 +197,6 @@ def download_stock_data(stock_code, period, start_date, end_date):
incrementally=True, incrementally=True,
) )
print("📊 正在获取市场数据...")
history_data = xtdata.get_market_data_ex( history_data = xtdata.get_market_data_ex(
g_fields, g_fields,
[stock_code], [stock_code],
@ -256,25 +244,19 @@ def process_stock_data(stock_code, stock_data):
>>> print(df.index.dtype) # datetime64[ns] >>> print(df.index.dtype) # datetime64[ns]
>>> print(df.shape) # (2, 2) >>> print(df.shape) # (2, 2)
""" """
print(f"\n🔍 处理股票: {stock_code}")
# 转换为DataFrame(如果还不是的话) # 转换为DataFrame(如果还不是的话)
if isinstance(stock_data, pd.DataFrame): if isinstance(stock_data, pd.DataFrame):
df = stock_data.copy() # 直接使用现有的DataFrame df = stock_data.copy() # 直接使用现有的DataFrame
print(f"✅ {stock_code} 已经是DataFrame,直接使用")
else: else:
df = pd.DataFrame(stock_data) # 转换为DataFrame df = pd.DataFrame(stock_data) # 转换为DataFrame
print(f"🔄 {stock_code} 已转换为DataFrame")
# 如果有时间索引,使用conv_time转换时间格式 # 如果有时间索引,使用conv_time转换时间格式
if not df.empty and "time" in df.columns: if not df.empty and "time" in df.columns:
print(f"⏰ {stock_code} 正在转换时间格式...")
# 使用conv_time函数转换时间戳 # 使用conv_time函数转换时间戳
df["time"] = df["time"].apply(conv_time) df["time"] = df["time"].apply(conv_time)
# 再转换为pandas datetime格式并设置为索引 # 再转换为pandas datetime格式并设置为索引
df["time"] = pd.to_datetime(df["time"], format="%Y%m%d%H%M%S.%f") df["time"] = pd.to_datetime(df["time"], format="%Y%m%d%H%M%S.%f")
df.set_index("time", inplace=True) df.set_index("time", inplace=True)
print(f"✅ {stock_code} 时间格式转换完成")
return df return df
@ -293,10 +275,13 @@ def save_all_to_csv(processed_data, period, output_dir="data"):
""" """
csv_files = [] csv_files = []
# 检查全局变量是否启用CSV保存
if not g_save_csv:
return csv_files
for stock_code, df in processed_data.items(): for stock_code, df in processed_data.items():
csv_path = save_dataframe_to_csv(df, stock_code, period, output_dir) csv_path = save_dataframe_to_csv(df, stock_code, period, output_dir)
if csv_path: if csv_path:
print(f"🎉 {stock_code} 成功保存CSV: {csv_path}")
csv_files.append(csv_path) csv_files.append(csv_path)
return csv_files return csv_files
@ -321,7 +306,6 @@ def save_all_to_mysql(processed_data, stock_models):
stock_model = stock_models[stock_code] stock_model = stock_models[stock_code]
mysql_count = save_dataframe_to_mysql(df, stock_model) mysql_count = save_dataframe_to_mysql(df, stock_model)
if mysql_count: if mysql_count:
print(f"🎉 {stock_code} 成功保存MySQL: {mysql_count} 条记录")
mysql_records[stock_code] = mysql_count mysql_records[stock_code] = mysql_count
else: else:
print(f"❌ {stock_code} 未找到对应的数据库模型") print(f"❌ {stock_code} 未找到对应的数据库模型")
@ -365,11 +349,8 @@ def process_all_stocks(history_data, stock_codes):
processed_data = {} processed_data = {}
if not history_data: if not history_data:
print("⚠️ 未获取到历史数据")
return processed_data return processed_data
print(f"📊 获取到的数据包含股票: {list(history_data.keys())}")
for stock_code in stock_codes: for stock_code in stock_codes:
if stock_code in history_data: if stock_code in history_data:
stock_data = history_data[stock_code] stock_data = history_data[stock_code]
@ -379,9 +360,6 @@ def process_all_stocks(history_data, stock_codes):
if not df.empty: if not df.empty:
processed_data[stock_code] = df processed_data[stock_code] = df
print(f"✅ {stock_code} 数据处理完成: {df.shape}")
else:
print(f"⚠️ {stock_code} 处理后数据为空")
else: else:
print(f"⚠️ 未找到 {stock_code} 的数据") print(f"⚠️ 未找到 {stock_code} 的数据")
@ -440,21 +418,12 @@ def main():
✅ 成功处理所有周期数据 ✅ 成功处理所有周期数据
""" """
try: try:
print("🎯 数据处理模型主程序 (支持MySQL长连接 + 批量周期下载)") print("🎯 数据处理模型启动...")
print("=" * 60)
# 显示将要处理的配置信息
print(f"📊 股票代码: {', '.join(g_stock_code_list)}")
print(f"📈 数据周期: {', '.join(g_period_list)} ({len(g_period_list)}个周期)")
print(f"📅 时间范围: {g_start_date} ~ {g_end_date}")
print("=" * 60)
# 1. 初始化MySQL数据库连接 # 1. 初始化MySQL数据库连接
print("🔗 正在初始化MySQL数据库连接...")
if not init_database(): if not init_database():
print("❌ MySQL数据库连接失败,程序退出") print("❌ MySQL数据库连接失败,程序退出")
return return
print("✅ MySQL数据库连接成功,保持长连接状态")
# 统计总体结果 # 统计总体结果
all_csv_files = [] all_csv_files = []
@ -465,47 +434,48 @@ def main():
# 2. 循环处理每个数据周期 # 2. 循环处理每个数据周期
for period_index, current_period in enumerate(g_period_list, 1): for period_index, current_period in enumerate(g_period_list, 1):
try: try:
print(f"\n🔄 [{period_index}/{len(g_period_list)}] 开始处理周期: {current_period}")
print("-" * 50)
# 3. 下载当前周期的所有股票数据 # 3. 下载当前周期的所有股票数据
print(f"📥 正在下载 {current_period} 周期数据...")
history_data = {} history_data = {}
# 循环下载每个股票的数据 # 循环下载每个股票的数据
for stock_code in g_stock_code_list: for stock_code in g_stock_code_list:
try: try:
print(f"📥 下载 {stock_code} 的 {current_period} 数据...")
stock_history_data = download_stock_data( stock_history_data = download_stock_data(
stock_code, current_period, g_start_date, g_end_date stock_code, current_period, g_start_date, g_end_date
) )
# 将单个股票的数据合并到总数据字典中 # 将单个股票的数据合并到总数据字典中
if stock_history_data: if stock_history_data:
history_data.update(stock_history_data) history_data.update(stock_history_data)
else:
print(f"⚠️ {stock_code} 未获取到数据")
except Exception as e: except Exception as e:
print(f"❌ {stock_code} 下载失败: {e}") print(f"❌ {stock_code} 下载失败: {e}")
continue continue
# 4. 处理当前周期的所有股票数据 # 4. 处理当前周期的所有股票数据
print(f"💾 开始处理 {len(g_stock_code_list)} 个股票的 {current_period} 数据...")
processed_data = process_all_stocks(history_data, g_stock_code_list) processed_data = process_all_stocks(history_data, g_stock_code_list)
if not processed_data: if not processed_data:
print(f"⚠️ {current_period} 周期没有成功处理的股票数据,跳过...")
failed_periods.append(current_period) failed_periods.append(current_period)
continue continue
# 5a. 保存到CSV文件 # 5a. 保存到CSV文件
print(f"📁 保存 {current_period} 数据到CSV文件...") if g_save_csv:
csv_files = save_all_to_csv(processed_data, current_period) csv_files = save_all_to_csv(processed_data, current_period)
all_csv_files.extend(csv_files) all_csv_files.extend(csv_files)
else:
csv_files = save_all_to_csv(processed_data, current_period) # 仍然调用,但函数内部会跳过
# 5b. 保存到MySQL数据库 # 5b. 保存到MySQL数据库
print(f"🗄️ 保存 {current_period} 数据到MySQL数据库...")
print(f"🔄 创建 {current_period} 周期的MySQL数据表...")
stock_models = create_tables_for_stocks(g_stock_code_list, current_period) stock_models = create_tables_for_stocks(g_stock_code_list, current_period)
# 只清空当前周期要更新的表
from stock_models import clear_stock_table
for stock_code in processed_data.keys():
if stock_code in stock_models:
try:
clear_stock_table(stock_models[stock_code])
except Exception as e:
print(f"❌ 清空 {stock_code} 表失败: {e}")
mysql_records = save_all_to_mysql(processed_data, stock_models) mysql_records = save_all_to_mysql(processed_data, stock_models)
# 合并MySQL记录统计 # 合并MySQL记录统计
@ -514,7 +484,6 @@ def main():
all_mysql_records[key] = count all_mysql_records[key] = count
total_periods_processed += 1 total_periods_processed += 1
print(f"✅ {current_period} 周期处理完成!")
except Exception as e: except Exception as e:
print(f"❌ {current_period} 周期处理失败: {e}") print(f"❌ {current_period} 周期处理失败: {e}")
@ -522,33 +491,18 @@ def main():
continue continue
# 6. 显示最终处理结果统计 # 6. 显示最终处理结果统计
print("\n" + "=" * 60)
print("📈 批量数据处理完成总结:")
print(f"🎯 处理周期: {total_periods_processed}/{len(g_period_list)} 个成功")
if failed_periods:
print(f"❌ 失败周期: {', '.join(failed_periods)}")
# MySQL结果统计
mysql_total = sum(all_mysql_records.values())
print(f"🗄️ MySQL数据库记录: {mysql_total} 条")
for key, count in all_mysql_records.items():
print(f" 📊 {key}: {count} 条记录")
# CSV文件统计
csv_count = len(all_csv_files)
print(f"📁 CSV文件数量: {csv_count} 个")
for file_path in all_csv_files[:10]: # 只显示前10个文件,避免输出过长
print(f" 📁 {file_path}")
if csv_count > 10:
print(f" 📁 ... 及其他 {csv_count - 10} 个文件")
print("=" * 60)
if total_periods_processed > 0: if total_periods_processed > 0:
print(f"🎉 成功处理 {total_periods_processed} 个周期的数据,已保存到MySQL数据库和CSV文件!") mysql_total = sum(all_mysql_records.values())
print(f"✅ 成功处理 {total_periods_processed} 个周期,MySQL记录: {mysql_total} 条")
if g_save_csv:
csv_count = len(all_csv_files)
print(f"✅ CSV文件: {csv_count} 个")
else: else:
print("❌ 没有成功处理任何周期的数据") print("❌ 没有成功处理任何周期的数据")
if failed_periods:
print(f"⚠️ 失败周期: {', '.join(failed_periods)}")
except KeyboardInterrupt: except KeyboardInterrupt:
print("\n⚠️ 收到中断信号,停止数据处理") print("\n⚠️ 收到中断信号,停止数据处理")
except Exception as e: except Exception as e:
@ -557,9 +511,7 @@ def main():
traceback.print_exc() traceback.print_exc()
finally: finally:
# 6. 清理数据库连接 # 6. 清理数据库连接
print("🔒 正在关闭数据库连接...")
close_database() close_database()
print("✅ 数据库连接已安全关闭")
if __name__ == "__main__": if __name__ == "__main__":

View File

@ -28,7 +28,8 @@ from stock_models import create_tables_for_stocks
logging.basicConfig(level=logging.INFO) logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
# 设置中文字体支持 # 设置matplotlib为交互式模式,支持放大缩小和移动
plt.ion() # 开启交互模式
plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei'] # 中文字体 plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei'] # 中文字体
plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题 plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题
@ -136,6 +137,14 @@ class StockKlineViewer:
if not df.empty: if not df.empty:
df.set_index('time', inplace=True) df.set_index('time', inplace=True)
# 去除重复数据 - 保留第一条记录
original_len = len(df)
df = df[~df.index.duplicated(keep='first')]
if len(df) < original_len:
logger.info(f"🧹 检测到重复数据,已去重: {original_len} -> {len(df)} 条")
logger.info(f"✅ 成功读取 {len(df)} 条 {stock_code} 数据") logger.info(f"✅ 成功读取 {len(df)} 条 {stock_code} 数据")
logger.info(f"📅 数据时间范围: {df.index.min()} ~ {df.index.max()}") logger.info(f"📅 数据时间范围: {df.index.min()} ~ {df.index.max()}")
else: else:
@ -149,15 +158,14 @@ class StockKlineViewer:
traceback.print_exc() traceback.print_exc()
return pd.DataFrame() return pd.DataFrame()
def plot_kline_chart(self, df, stock_code, period, save_path=None, show_volume=True): def plot_kline_chart(self, df, stock_code, period, show_volume=True):
""" """
绘制K线图 绘制可交互的K线图
Args: Args:
df (pd.DataFrame): 包含OHLCV数据的DataFrame df (pd.DataFrame): 包含OHLCV数据的DataFrame
stock_code (str): 股票代码 stock_code (str): 股票代码
period (str): 数据周期 period (str): 数据周期
save_path (str, optional): 保存图片的路径,默认不保存
show_volume (bool): 是否显示成交量,默认True show_volume (bool): 是否显示成交量,默认True
Returns: Returns:
@ -168,19 +176,23 @@ class StockKlineViewer:
return False return False
try: try:
# 创建新的figure窗口
plt.figure(figsize=(16, 10))
# 创建图表布局 # 创建图表布局
if show_volume: if show_volume:
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(15, 10), ax1 = plt.subplot(2, 1, 1) # K线图占上面3/4
gridspec_kw={'height_ratios': [3, 1]}, ax2 = plt.subplot(2, 1, 2) # 成交量图占下面1/4
sharex=True) plt.subplots_adjust(hspace=0.3) # 调整子图间距
else: else:
fig, ax1 = plt.subplots(1, 1, figsize=(15, 8)) ax1 = plt.subplot(1, 1, 1)
# 绘制K线图 # 绘制K线图
self._plot_candlestick(ax1, df) self._plot_candlestick(ax1, df)
# 设置K线图标题和标签 # 设置K线图标题和标签
ax1.set_title(f'{stock_code} K线图 ({period}周期)', fontsize=16, fontweight='bold') ax1.set_title(f'{stock_code} K线图 ({period}周期) - 数据总数: {len(df)}条',
fontsize=16, fontweight='bold')
ax1.set_ylabel('价格 (元)', fontsize=12) ax1.set_ylabel('价格 (元)', fontsize=12)
ax1.grid(True, alpha=0.3) ax1.grid(True, alpha=0.3)
@ -193,16 +205,23 @@ class StockKlineViewer:
# 设置x轴时间格式 # 设置x轴时间格式
self._setup_time_axis(ax2 if show_volume else ax1, df.index) self._setup_time_axis(ax2 if show_volume else ax1, df.index)
# 调整布局 # 启用工具栏和交互功能
plt.tight_layout() plt.tight_layout()
# 保存图片 # 显示交互式图表
if save_path: logger.info("📈 K线图已显示,可以使用工具栏进行放大、缩小、移动等操作")
plt.savefig(save_path, dpi=300, bbox_inches='tight') logger.info("💡 使用提示:")
logger.info(f"📈 K线图已保存到: {save_path}") logger.info(" - 🔍 放大镜工具:框选区域进行放大")
logger.info(" - ↔️ 移动工具:拖拽图表进行移动")
logger.info(" - 🏠 主页按钮:恢复到原始视图")
logger.info(" - ⬅️ 后退按钮:返回上一个视图")
plt.show(block=False) # 非阻塞显示,允许继续执行程序
# 等待用户交互
input("\n按回车键关闭图表窗口...")
plt.close()
# 显示图表
plt.show()
logger.info("✅ K线图绘制完成") logger.info("✅ K线图绘制完成")
return True return True
@ -220,36 +239,46 @@ class StockKlineViewer:
ax: matplotlib轴对象 ax: matplotlib轴对象
df: 包含OHLC数据的DataFrame df: 包含OHLC数据的DataFrame
""" """
# 计算K线颜色 (红涨绿跌) # 重置DataFrame索引,确保能正确遍历
up_mask = df['close'] >= df['open'] df_reset = df.reset_index()
down_mask = df['close'] < df['open']
# 绘制上涨K线 (红色) # 绘制每根K线
for i, (time, row) in enumerate(df[up_mask].iterrows()): for i, row in df_reset.iterrows():
# K线实体 # 确定K线颜色 (红涨绿跌)
height = row['close'] - row['open'] if row['close'] >= row['open']:
ax.add_patch(Rectangle((i-0.3, row['open']), 0.6, height, # 上涨K线 (红色)
facecolor='red', edgecolor='red', alpha=0.8)) color = 'red'
# 上影线 # K线实体
ax.plot([i, i], [row['close'], row['high']], color='red', linewidth=1) height = row['close'] - row['open']
# 下影线 body_bottom = row['open']
ax.plot([i, i], [row['open'], row['low']], color='red', linewidth=1) else:
# 下跌K线 (绿色)
color = 'green'
# K线实体
height = row['open'] - row['close']
body_bottom = row['close']
# 绘制K线实体
if height > 0: # 有实体
ax.add_patch(Rectangle((i-0.3, body_bottom), 0.6, height,
facecolor=color, edgecolor=color, alpha=0.8))
else: # 十字星,实体高度为0
ax.plot([i-0.3, i+0.3], [row['open'], row['open']], color=color, linewidth=2)
# 绘制上影线
if row['high'] > max(row['open'], row['close']):
ax.plot([i, i], [max(row['open'], row['close']), row['high']], color=color, linewidth=1)
# 绘制下影线
if row['low'] < min(row['open'], row['close']):
ax.plot([i, i], [row['low'], min(row['open'], row['close'])], color=color, linewidth=1)
# 绘制下跌K线 (绿色) # 设置坐标轴范围
for i, (time, row) in enumerate(df[down_mask].iterrows()): ax.set_xlim(-0.5, len(df_reset)-0.5)
# K线实体 price_min = df['low'].min()
height = row['open'] - row['close'] price_max = df['high'].max()
ax.add_patch(Rectangle((i-0.3, row['close']), 0.6, height, price_range = price_max - price_min
facecolor='green', edgecolor='green', alpha=0.8)) ax.set_ylim(price_min - price_range * 0.05, price_max + price_range * 0.05)
# 上影线
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): def _plot_volume(self, ax, df):
""" """
@ -289,17 +318,26 @@ class StockKlineViewer:
ax: matplotlib轴对象 ax: matplotlib轴对象
time_index: 时间索引 time_index: 时间索引
""" """
# 设置x轴标签为时间 # 设置x轴标签为时间,适合日线显示
step = max(1, len(time_index) // 10) # 最多显示10个时间标签 step = max(1, len(time_index) // 8) # 最多显示8个时间标签,避免过密
time_labels = [time_index[i].strftime('%m-%d %H:%M') if hasattr(time_index[i], 'strftime') time_labels = []
else str(time_index[i]) for i in range(0, len(time_index), step)] tick_positions = []
tick_positions = list(range(0, len(time_index), step))
for i in range(0, len(time_index), step):
if i < len(time_index):
time_val = time_index[i]
if hasattr(time_val, 'strftime'):
# 日线显示格式:月-日
time_labels.append(time_val.strftime('%m-%d'))
else:
time_labels.append(str(time_val))
tick_positions.append(i)
ax.set_xticks(tick_positions) ax.set_xticks(tick_positions)
ax.set_xticklabels(time_labels, rotation=45, ha='right') ax.set_xticklabels(time_labels, rotation=45, ha='right')
ax.set_xlabel('时间', fontsize=12) ax.set_xlabel('时间', fontsize=12)
def view_stock_kline(self, stock_code, period, start_date, end_date, save_chart=True): def view_stock_kline(self, stock_code, period, start_date, end_date):
""" """
查看股票K线图的完整流程 查看股票K线图的完整流程
@ -308,7 +346,6 @@ class StockKlineViewer:
period (str): 数据周期 period (str): 数据周期
start_date (str): 开始日期 start_date (str): 开始日期
end_date (str): 结束日期 end_date (str): 结束日期
save_chart (bool): 是否保存图表
Returns: Returns:
bool: 成功返回True,失败返回False bool: 成功返回True,失败返回False
@ -329,16 +366,8 @@ class StockKlineViewer:
logger.error(f"❌ {stock_code} 在指定时间范围内没有数据") logger.error(f"❌ {stock_code} 在指定时间范围内没有数据")
return False return False
# 3. 生成保存路径(可选) # 3. 绘制交互式K线图
save_path = None success = self.plot_kline_chart(df, stock_code, period)
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: if success:
logger.info("🎉 K线图查看完成!") logger.info("🎉 K线图查看完成!")
@ -353,35 +382,29 @@ class StockKlineViewer:
traceback.print_exc() traceback.print_exc()
return False return False
finally: finally:
# 5. 清理资源 # 4. 清理资源
self.disconnect_database() self.disconnect_database()
def main(): def main():
""" """
主函数 - 测试K线图查看器 主函数 - 测试K线图查看器(专注于日线数据)
""" """
try: try:
# 创建K线图查看器 # 创建K线图查看器
viewer = StockKlineViewer() viewer = StockKlineViewer()
# 测试参数 - 与main.py保持一致 # 测试参数 - 专注于日线数据
test_cases = [ test_cases = [
{ {
"stock_code": "601658.SH", "stock_code": "601658.SH", # 邮储银行
"period": "1d", "period": "1d",
"start_date": "20250501", "start_date": "20250501",
"end_date": "20250721"
},
{
"stock_code": "510310.SH",
"period": "1m",
"start_date": "20250701",
"end_date": "20250721" "end_date": "20250721"
} }
] ]
print("🚀 股票K线图查看器测试") print("🚀 股票K线图查看器测试 - 日线数据")
print("=" * 50) print("=" * 50)
for i, test_case in enumerate(test_cases, 1): for i, test_case in enumerate(test_cases, 1):
@ -394,8 +417,7 @@ def main():
stock_code=test_case['stock_code'], stock_code=test_case['stock_code'],
period=test_case['period'], period=test_case['period'],
start_date=test_case['start_date'], start_date=test_case['start_date'],
end_date=test_case['end_date'], end_date=test_case['end_date']
save_chart=True
) )
if success: if success:

View File

@ -16,8 +16,8 @@ class StockKlineBase(BaseModel):
股票K线数据基础模型 股票K线数据基础模型
这是所有股票K线表的基础模型,定义了通用字段 这是所有股票K线表的基础模型,定义了通用字段
""" """
# 时间戳字段 # 时间戳字段 - 设置为主键确保唯一性
timestamp = DateTimeField(index=True, help_text="K线时间戳") timestamp = DateTimeField(primary_key=True, help_text="K线时间戳")
# OHLCV数据 - 使用Decimal确保精度 # OHLCV数据 - 使用Decimal确保精度
open_price = DecimalField(max_digits=10, decimal_places=3, help_text="开盘价") open_price = DecimalField(max_digits=10, decimal_places=3, help_text="开盘价")
@ -30,10 +30,6 @@ class StockKlineBase(BaseModel):
# 创建和更新时间 # 创建和更新时间
created_at = DateTimeField(default=datetime.now, help_text="记录创建时间") created_at = DateTimeField(default=datetime.now, help_text="记录创建时间")
updated_at = DateTimeField(default=datetime.now, help_text="记录更新时间") updated_at = DateTimeField(default=datetime.now, help_text="记录更新时间")
class Meta:
# 设置时间戳字段为主键(确保每个时间点只有一条记录)
primary_key = False
def create_stock_kline_model(stock_code: str, period: str = "1d"): def create_stock_kline_model(stock_code: str, period: str = "1d"):
""" """
@ -60,8 +56,7 @@ def create_stock_kline_model(stock_code: str, period: str = "1d"):
'__module__': __name__, '__module__': __name__,
'Meta': type('Meta', (), { 'Meta': type('Meta', (), {
'table_name': table_name, 'table_name': table_name,
'database': get_database(), 'database': get_database()
'primary_key': False
}), }),
'stock_code': stock_code, # 保存原始股票代码 'stock_code': stock_code, # 保存原始股票代码
}) })
@ -124,33 +119,33 @@ def save_dataframe_to_mysql(df, stock_model, batch_size=1000):
return 0 return 0
try: try:
# 准备批量插入的数据 # 由于timestamp现在是主键,我们需要逐条插入,忽略重复记录
batch_data = [] success_count = 0
for timestamp, row in df.iterrows(): for timestamp, row in df.iterrows():
record = { try:
'timestamp': timestamp, # 尝试插入记录,如果timestamp重复则跳过
'open_price': Decimal(str(row['open'])), stock_model.insert(
'high_price': Decimal(str(row['high'])), timestamp=timestamp,
'low_price': Decimal(str(row['low'])), open_price=Decimal(str(row['open'])),
'close_price': Decimal(str(row['close'])), high_price=Decimal(str(row['high'])),
'volume': int(row['volume']), low_price=Decimal(str(row['low'])),
'amount': Decimal(str(row['amount'])) if 'amount' in row else Decimal('0') close_price=Decimal(str(row['close'])),
} volume=int(row['volume']),
batch_data.append(record) amount=Decimal(str(row['amount'])) if 'amount' in row else Decimal('0')
).execute()
# 当达到批量大小时执行插入 success_count += 1
if len(batch_data) >= batch_size: except Exception as e:
stock_model.insert_many(batch_data).execute() # 如果是重复键错误,说明主键约束生效,静默跳过
batch_data = [] if "Duplicate entry" in str(e) or "PRIMARY" in str(e):
continue # 静默跳过重复的timestamp
# 插入剩余数据 else:
if batch_data: logger.warning(f"⚠️ 插入记录失败 {timestamp}: {e}")
stock_model.insert_many(batch_data).execute() continue
total_records = len(df) total_records = len(df)
logger.info(f"✅ 成功保存 {total_records} 条K线数据到数据库") logger.info(f"✅ 成功保存 {success_count}/{total_records} 条K线数据到数据库")
return total_records return success_count
except Exception as e: except Exception as e:
logger.error(f"❌ 保存K线数据到数据库失败: {e}") logger.error(f"❌ 保存K线数据到数据库失败: {e}")
@ -187,3 +182,70 @@ def get_stock_kline_data(stock_model, start_time=None, end_time=None, limit=None
except Exception as e: except Exception as e:
logger.error(f"❌ 查询K线数据失败: {e}") logger.error(f"❌ 查询K线数据失败: {e}")
raise raise
def clear_stock_table(stock_model):
"""
清空股票K线数据表
Args:
stock_model: 股票K线数据模型类
Returns:
int: 删除的记录数量
"""
try:
# 获取表名用于日志显示
table_name = stock_model._meta.table_name
# 先查询记录数量
count_before = stock_model.select().count()
if count_before > 0:
logger.info(f"🧹 正在清空表 {table_name},当前记录数: {count_before}")
# 删除所有记录
deleted_count = stock_model.delete().execute()
logger.info(f"✅ 成功清空表 {table_name},删除了 {deleted_count} 条记录")
return deleted_count
else:
logger.info(f"ℹ️ 表 {table_name} 已经是空的,无需清空")
return 0
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

View File

@ -1,158 +0,0 @@
"""
测试股票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()