diff --git a/src/data_process_model/main.py b/src/data_process_model/main.py index 5c5951b..67c821a 100644 --- a/src/data_process_model/main.py +++ b/src/data_process_model/main.py @@ -19,8 +19,7 @@ g_start_date = "20250101" # 开始日期 # 选项2: 手动指定确切日期 (推荐用于调试) g_end_date = "20250728" # 手动指定到7月28日 -print(f"🗓️ 数据请求日期范围: {g_start_date} ~ {g_end_date}") -print(f"📅 当前系统时间: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") +print(f"🗓️ 数据范围: {g_start_date} ~ {g_end_date}") # CSV文件保存控制变量 # 说明:设置为 True 启用CSV文件保存,False 则只保存到MySQL数据库 @@ -187,11 +186,8 @@ def download_stock_data(stock_code, period, start_date, end_date): >>> if data and "601658.SH" in data: >>> print(f"601658.SH: {len(data['601658.SH']['time'])} 条数据") """ - print(f"📥 正在下载 {stock_code} ({period}) 数据: {start_date} ~ {end_date}") - - # 尝试不使用增量模式下载,以获取完整历史数据 + # 尝试下载数据 try: - print(" 🔄 尝试完整模式下载...") xtdata.download_history_data( stock_code, period, @@ -199,11 +195,8 @@ def download_stock_data(stock_code, period, start_date, end_date): end_date, incrementally=False, # 改为False,强制下载完整历史数据 ) - print(f" ✅ {stock_code} 历史数据下载完成 (完整模式)") - except Exception as e: - print(f" ⚠️ {stock_code} 完整模式下载失败,尝试增量模式: {e}") + except Exception: try: - print(" 🔄 尝试增量模式下载...") xtdata.download_history_data( stock_code, period, @@ -211,12 +204,11 @@ def download_stock_data(stock_code, period, start_date, end_date): end_date, incrementally=True, # 备用增量模式 ) - print(f" ✅ {stock_code} 历史数据下载完成 (增量模式)") - except Exception as e2: - print(f" ❌ {stock_code} 增量模式也失败: {e2}") + except Exception as e: + print(f"❌ {stock_code} 下载失败: {e}") return {} - # 获取市场数据 + # 获取市场数据并验证 history_data = xtdata.get_market_data_ex( g_fields, [stock_code], @@ -225,49 +217,24 @@ def download_stock_data(stock_code, period, start_date, end_date): end_time=end_date, ) - # 验证数据范围和质量 + # 简单数据验证 if history_data and stock_code in history_data: data = history_data[stock_code] if 'time' in data and len(data['time']) > 0: - # 转换时间戳以显示实际数据范围 - first_time = conv_time(data['time'][0]) - last_time = conv_time(data['time'][-1]) data_count = len(data['time']) + print(f"✅ {stock_code}({period}): {data_count} 条记录") - print(f" 📊 {stock_code} 数据统计:") - print(f" - 记录数: {data_count} 条") - print(f" - 时间范围: {first_time[:8]} ~ {last_time[:8]}") - print(f" - 请求范围: {start_date} ~ {end_date}") - - # 检查数据起始时间 - request_start = start_date - actual_start = first_time[:8] - if actual_start > request_start: - print(" ⚠️ 数据起始时间晚于请求时间:") - print(f" 请求: {request_start}, 实际: {actual_start}") - print(" 可能原因: 数据提供商限制、股票上市时间、停牌期间") - - # 检查数据结束时间 - request_end = end_date + # 只显示严重的时间范围问题 + last_time = conv_time(data['time'].iloc[-1]) actual_end = last_time[:8] - if actual_end < request_end: - print(" ⚠️ 数据结束时间早于请求时间:") - print(f" 请求: {request_end}, 实际: {actual_end}") - print(" 可能原因: 数据更新延迟、交易日历限制、数据源问题") - - # 计算缺失的天数 - from datetime import datetime - try: - req_date = datetime.strptime(request_end, '%Y%m%d') - act_date = datetime.strptime(actual_end, '%Y%m%d') - missing_days = (req_date - act_date).days - print(f" 缺失天数: {missing_days} 天") - except Exception as e: - print(f" 日期计算失败: {e}") + if actual_end < end_date: + print(f"⚠️ {stock_code} 数据到 {actual_end},请求到 {end_date}") else: - print(f" ❌ {stock_code} 没有获取到有效数据") + print(f"❌ {stock_code} 无有效数据") + return {} else: - print(f" ❌ {stock_code} 数据下载失败或格式异常") + print(f"❌ {stock_code} 下载失败") + return {} return history_data @@ -365,18 +332,14 @@ def save_all_to_mysql(processed_data, stock_models): from stock_models import save_dataframe_to_mysql, save_dataframe_to_mysql_replace_mode mysql_records = {} - print(f"💾 数据库插入模式: {g_insert_mode}") - for stock_code, df in processed_data.items(): if stock_code in stock_models: stock_model = stock_models[stock_code] try: if g_insert_mode == "replace": - # 替换模式:清空表后重新插入 mysql_count = save_dataframe_to_mysql_replace_mode(df, stock_model) else: - # 增量模式:只插入新数据(默认) mysql_count = save_dataframe_to_mysql(df, stock_model) if mysql_count: @@ -386,7 +349,7 @@ def save_all_to_mysql(processed_data, stock_models): print(f"❌ {stock_code} 数据保存失败: {e}") continue else: - print(f"❌ {stock_code} 未找到对应的数据库模型") + print(f"❌ {stock_code} 未找到数据库模型") return mysql_records @@ -438,8 +401,6 @@ def process_all_stocks(history_data, stock_codes): if not df.empty: processed_data[stock_code] = df - else: - print(f"⚠️ 未找到 {stock_code} 的数据") return processed_data @@ -496,80 +457,51 @@ def main(): ✅ 成功处理所有周期数据 """ try: - print("🎯 数据处理模型启动...") + print("🎯 数据处理启动...") - # 1. 初始化MySQL数据库连接 + # 初始化数据库 if not init_database(): - print("❌ MySQL数据库连接失败,程序退出") + print("❌ 数据库连接失败") return - # 统计总体结果 - all_csv_files = [] + # 统计结果 all_mysql_records = {} total_periods_processed = 0 failed_periods = [] - # 2. 循环处理每个数据周期 - for period_index, current_period in enumerate(g_period_list, 1): + # 处理每个周期 + for current_period in g_period_list: try: - # 3. 下载当前周期的所有股票数据 - history_data = {} + print(f"\n📊 处理周期: {current_period}") - # 循环下载每个股票的数据 + # 下载数据 + history_data = {} for stock_code in g_stock_code_list: try: stock_history_data = download_stock_data( stock_code, current_period, g_start_date, g_end_date ) - # 将单个股票的数据合并到总数据字典中 if stock_history_data: history_data.update(stock_history_data) except Exception as e: print(f"❌ {stock_code} 下载失败: {e}") continue - # 4. 处理当前周期的所有股票数据 + # 处理数据 processed_data = process_all_stocks(history_data, g_stock_code_list) - if not processed_data: failed_periods.append(current_period) continue - # 5a. 保存到CSV文件 - if g_save_csv: - csv_files = save_all_to_csv(processed_data, current_period) - all_csv_files.extend(csv_files) - else: - csv_files = save_all_to_csv(processed_data, current_period) # 仍然调用,但函数内部会跳过 - - # 5b. 保存到MySQL数据库 + # 保存到数据库 stock_models = create_tables_for_stocks(g_stock_code_list, current_period) - - # 注意:不再自动清空表,改为智能增量插入 - # 如果需要清空表重新插入,请将 g_insert_mode 设置为 "replace" mysql_records = save_all_to_mysql(processed_data, stock_models) - # 合并MySQL记录统计 + # 统计记录 for stock_code, count in mysql_records.items(): key = f"{stock_code}_{current_period}" all_mysql_records[key] = count - # 显示当前周期的数据范围摘要 - print(f"\n📊 {current_period} 周期数据摘要:") - for stock_code, df in processed_data.items(): - if not df.empty: - start_time = df.index.min().strftime('%Y-%m-%d') - end_time = df.index.max().strftime('%Y-%m-%d') - record_count = len(df) - print(f" {stock_code}: {record_count} 条记录, {start_time} ~ {end_time}") - - # 检查是否有数据缺失 - request_start_datetime = pd.to_datetime(g_start_date, format='%Y%m%d') - actual_start_datetime = df.index.min() - if actual_start_datetime.date() > request_start_datetime.date(): - days_missing = (actual_start_datetime.date() - request_start_datetime.date()).days - print(f" ⚠️ 数据起始延迟 {days_missing} 天") - total_periods_processed += 1 except Exception as e: @@ -577,27 +509,23 @@ def main(): failed_periods.append(current_period) continue - # 6. 显示最终处理结果统计 + # 显示最终结果 if total_periods_processed > 0: 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} 个") + print(f"\n✅ 处理完成: {total_periods_processed} 周期, {mysql_total} 条记录") else: - print("❌ 没有成功处理任何周期的数据") + print("\n❌ 所有周期处理失败") if failed_periods: print(f"⚠️ 失败周期: {', '.join(failed_periods)}") except KeyboardInterrupt: - print("\n⚠️ 收到中断信号,停止数据处理") + print("\n⚠️ 用户中断") except Exception as e: - print(f"\n❌ 程序执行出错: {e}") + print(f"\n❌ 程序异常: {e}") import traceback traceback.print_exc() finally: - # 6. 清理数据库连接 close_database()