QTrade/src/data_process_model/main.py

585 lines
21 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import datetime
import pandas as pd
from xtquant import xtdata
import time
# 导入公共配置
from common import (
normalize_stock_code,
LOG_PREFIXES, KLINE_COLUMNS, TimeFrame,
TIME_FORMATS
)
# 导入新的双层架构模块
from stockdata_manager import get_stock_data_manager
# ============== 全局配置参数 ==============
# 使用标准化的股票代码格式
g_stock_code_list = [
#normalize_stock_code("601658.SH"),
#normalize_stock_code("510310.SH"),
normalize_stock_code("601398.SH"),
#normalize_stock_code("601288.SH"),
#normalize_stock_code("601609.SH"),
#normalize_stock_code("601288.SH"),
normalize_stock_code("300339.SZ")
] # 标准化后的股票代码
# 调整时间范围到最近的一个月,避免跨度过大导致数据获取问题
# xtquant API 要求:支持格式 YYYYMMDD 或 YYYYMMDDhhmmss
# 若取某日全量历史数据,时间需要具体到秒,如 "20200427093000"
# 开始时间:7月1日 09:30:00 (交易开始时间)
g_start_date = "20250101093000"
# 结束时间选项
# 选项1: 使用当前日期时间,精确到秒 (推荐用于获取最新数据)
current_time = datetime.datetime.now()
g_end_date = current_time.strftime("%Y%m%d%H%M%S")
# 选项2: 手动指定确切日期时间 (推荐用于调试和稳定获取数据)
# g_end_date = "20250731150000" # 7月31日 15:00:00 (交易结束时间)
# 选项3: 只使用日期格式(适用于日线及以上周期)
# g_start_date = "20250701"
# g_end_date = "20250731"
print(f"{LOG_PREFIXES['TIME']} 数据范围: {g_start_date} ~ {g_end_date}")
# 数据库插入模式配置
# 说明:控制数据保存策略,提升插入性能
# - "incremental": 增量模式,只插入新数据,跳过已存在的记录 (推荐)
# - "replace": 替换模式,清空表后重新插入所有数据 (适用于数据修正)
g_insert_mode = "incremental" # 恢复增量插入模式
''''
"1m", # 1分钟
"5m", # 5分钟
"15m", # 15分钟
"30m", # 30分钟
"60m", # 60分钟
"1d", # 日线
"1w", # 周线
"1mon", # 月线
"1q", # 季线
"1hy", # 半年线
"1y", # 年线
]'''
# 使用公共配置中的时间周期定义
g_period_list = [
TimeFrame.MINUTE_1.value, # "1m" - 1分钟
TimeFrame.MINUTE_5.value, # "5m" - 5分钟
TimeFrame.MINUTE_15.value, # "15m" - 15分钟
TimeFrame.MINUTE_30.value, # "30m" - 30分钟
TimeFrame.MINUTE_60.value, # "60m" - 60分钟 (1小时)
TimeFrame.DAILY.value # "1d" - 日线
]
"""
'time' #时间戳
'open' #开盘价
'high' #最高价
'low' #最低价
'close' #收盘价
'volume' #成交量
'amount' #成交额
'settelementPrice' #今结算
'openInterest' #持仓量
'preClose' #前收价
'suspendFlag' #停牌标记 0 - 正常 1 - 停牌 -1 - 当日起复牌
"""
g_fields = ["time", "open", "high", "low", "close", "volume", "amount"]
def format_time_for_xtquant(dt=None, format_type="full"):
"""
为 xtquant API 格式化时间
Args:
dt (datetime): 时间对象,None 则使用当前时间
format_type (str): 格式类型
- "full": YYYYMMDDhhmmss (完整时间,推荐用于分钟级数据)
- "date": YYYYMMDD (仅日期,适用于日线及以上周期)
- "trading_start": 当日交易开始时间 (09:30:00)
- "trading_end": 当日交易结束时间 (15:00:00)
Returns:
str: 格式化的时间字符串
Example:
>>> format_time_for_xtquant()
'20250805131045'
>>> format_time_for_xtquant(format_type="date")
'20250805'
>>> format_time_for_xtquant(format_type="trading_start")
'20250805093000'
"""
if dt is None:
dt = datetime.datetime.now()
if format_type == "full":
return dt.strftime("%Y%m%d%H%M%S")
elif format_type == "date":
return dt.strftime("%Y%m%d")
elif format_type == "trading_start":
return dt.strftime("%Y%m%d") + "093000"
elif format_type == "trading_end":
return dt.strftime("%Y%m%d") + "150000"
else:
return dt.strftime("%Y%m%d%H%M%S")
def get_trading_time_range(start_date_str, end_date_str=None, time_format="full"):
"""
获取交易时间范围
Args:
start_date_str (str): 开始日期,如 "20240101"
end_date_str (str): 结束日期,None 则使用当前日期
time_format (str): 时间格式类型
Returns:
tuple: (start_time, end_time) 时间字符串元组
"""
# 解析开始日期
start_dt = datetime.datetime.strptime(start_date_str, "%Y%m%d")
start_time = format_time_for_xtquant(start_dt, "trading_start")
# 解析结束日期
if end_date_str:
end_dt = datetime.datetime.strptime(end_date_str, "%Y%m%d")
else:
end_dt = datetime.datetime.now()
if time_format == "full":
end_time = format_time_for_xtquant(end_dt, "trading_end")
else:
end_time = format_time_for_xtquant(end_dt, "date")
return start_time, end_time
def conv_time(ct):
"""
将时间戳转换为格式化时间字符串
将Unix毫秒时间戳转换为标准时间格式
使用公共配置中定义的时间格式标准
Args:
ct (float): Unix时间戳(毫秒),如 1476374400000
Returns:
str: 格式化的时间字符串,如 '20161014000000.000'
Example:
>>> conv_time(1476374400000)
'20161014000000.000'
"""
local_time = time.localtime(ct / 1000)
data_head = time.strftime(TIME_FORMATS['COMPACT'].replace('_', ''), local_time)
data_secs = (ct - int(ct)) * 1000
time_stamp = "%s.%03d" % (data_head, data_secs)
return time_stamp
def download_stock_data(stock_code, period, start_date, end_date):
"""
下载单个股票的历史数据
从xtquant数据中心下载指定股票的历史行情数据,
支持增量下载模式,可获取指定时间段内的完整历史数据
Args:
stock_code (str): 单个股票代码,如 "601658.SH", "000001.SZ", "300750.SZ"
period (str): 数据周期标识,支持格式:
- 分钟级: "1m", "5m", "15m", "30m", "60m"
- 日级: "1d"
- 其他: "1w", "1M"
start_date (str): 开始日期,格式为 "YYYYMMDD"
如 "20240101", "20231201"
end_date (str): 结束日期,格式为 "YYYYMMDD"
如 "20241231", "20240131"
Returns:
dict: 历史数据字典,结构如下:
{
"stock_code": {
'time': [timestamp1, timestamp2, ...],
'open': [price1, price2, ...],
'high': [price1, price2, ...],
'low': [price1, price2, ...],
'close': [price1, price2, ...],
'volume': [vol1, vol2, ...],
'amount': [amt1, amt2, ...]
}
}
如果下载失败,返回空字典或包含None值的字典
Raises:
Exception: 当网络连接失败或API调用异常时抛出
Example:
>>> data = download_stock_data("601658.SH", "1d", "20240101", "20241231")
>>> if data and "601658.SH" in data:
>>> print(f"601658.SH: {len(data['601658.SH']['time'])} 条数据")
"""
# 尝试下载数据
try:
xtdata.download_history_data(
stock_code,
period,
start_date,
end_date,
incrementally=False, # 改为False,强制下载完整历史数据
)
except Exception:
try:
xtdata.download_history_data(
stock_code,
period,
start_date,
end_date,
incrementally=True, # 备用增量模式
)
except Exception as e:
print(f"{LOG_PREFIXES['ERROR']} {stock_code} 下载失败: {e}")
return {}
# 获取市场数据并验证
history_data = xtdata.get_market_data_ex(
g_fields,
[stock_code],
period=period,
start_time=start_date,
end_time=end_date,
)
# 简单数据验证
if history_data and stock_code in history_data:
data = history_data[stock_code]
# 修复DataFrame布尔判断问题 - 检查数据不为空且包含必要字段
if data is not None and 'time' in data and len(data['time']) > 0:
data_count = len(data['time'])
print(f"{LOG_PREFIXES['SUCCESS']} {stock_code}({period}): {data_count} 条记录")
# 只显示严重的时间范围问题
last_time = conv_time(data['time'].iloc[-1])
actual_end = last_time[:8]
if actual_end < end_date:
print(f"{LOG_PREFIXES['WARNING']} {stock_code} 数据到 {actual_end},请求到 {end_date}")
else:
print(f"{LOG_PREFIXES['ERROR']} {stock_code} 无有效数据")
return {}
else:
print(f"{LOG_PREFIXES['ERROR']} {stock_code} 下载失败")
return {}
return history_data
def process_stock_data(stock_code, stock_data):
"""
处理单个股票的原始数据并转换为pandas DataFrame
使用公共配置的标准时间格式和列名约定
Args:
stock_code (str): 股票代码,用于日志输出和错误追踪
stock_data: 股票原始数据
Returns:
pd.DataFrame: 处理后的pandas DataFrame,符合公共配置的标准格式
"""
# 转换为DataFrame(如果还不是的话)
if isinstance(stock_data, pd.DataFrame):
df = stock_data.copy() # 直接使用现有的DataFrame
else:
df = pd.DataFrame(stock_data) # 转换为DataFrame
# 如果有时间索引,使用conv_time转换时间格式
if not df.empty and "time" in df.columns:
# 使用conv_time函数转换时间戳
df["time"] = df["time"].apply(conv_time)
# 再转换为pandas datetime格式并重命名为标准列名
df[KLINE_COLUMNS['timestamp']] = pd.to_datetime(df["time"], format="%Y%m%d%H%M%S.%f")
df.set_index(KLINE_COLUMNS['timestamp'], inplace=True)
# 删除原始time列
if "time" in df.columns:
df.drop("time", axis=1, inplace=True)
return df
def save_all_to_mysql(processed_data, data_manager, current_period):
"""
将所有处理过的股票数据保存到MySQL数据库 - 使用新的双层架构
Args:
processed_data (dict): 处理过的股票数据字典 {stock_code: DataFrame}
data_manager: StockDataManager实例
current_period: 当前数据周期
Returns:
dict: 保存结果字典 {stock_code: record_count}
"""
mysql_records = {}
for stock_code, df in processed_data.items():
try:
# 使用新的架构保存数据
count = data_manager.save_dataframe(df, stock_code, current_period, mode=g_insert_mode)
if count > 0:
mysql_records[stock_code] = count
print(f"{LOG_PREFIXES['SUCCESS']} {stock_code} 保存 {count} 条记录到数据库")
else:
print(f"{LOG_PREFIXES['WARNING']} {stock_code} 没有新数据保存")
except Exception as e:
print(f"{LOG_PREFIXES['ERROR']} {stock_code} 数据保存失败: {e}")
continue
return mysql_records
def process_all_stocks(history_data, stock_codes):
"""
批量处理所有股票数据,转换为DataFrame格式
对历史数据字典中的每个股票进行数据处理和格式化,
转换为标准的pandas DataFrame格式,但不进行保存操作
Args:
history_data (dict): 历史数据字典,包含多个股票的原始数据
格式: {stock_code: raw_data, ...}
其中raw_data包含time, open, high, low, close等字段
stock_codes (list): 需要处理的股票代码列表
如 ["601658.SH", "000001.SZ", "300750.SZ"]
用于遍历和验证数据完整性
Returns:
dict: 处理过的股票数据字典,格式如下:
{
'stock1': DataFrame1,
'stock2': DataFrame2,
...
}
如果某个股票处理失败,对应的结果不会出现在字典中
Example:
>>> history_data = {
>>> "601658.SH": {"time": [123456], "close": [10.5]},
>>> "000001.SZ": {"time": [123457], "close": [15.2]}
>>> }
>>> codes = ["601658.SH", "000001.SZ"]
>>> processed = process_all_stocks(history_data, codes)
>>> print(f"处理了 {len(processed)} 个股票")
"""
processed_data = {}
if not history_data:
return processed_data
for stock_code in stock_codes:
if stock_code in history_data:
stock_data = history_data[stock_code]
# 处理单个股票数据
df = process_stock_data(stock_code, stock_data)
if not df.empty:
processed_data[stock_code] = df
return processed_data
# 订阅行情
def subscribe_stocks_periods(stock_codes, periods, start_time='', end_time='', count=-1):
"""
订阅指定股票和周期的行情数据
Args:
stock_codes (list): 股票代码列表,如 ["601658.SH", "000001.SZ"]
periods (list): 数据周期列表,如 ["1m", "5m", "1d"]
start_time (str): 开始时间,支持格式:
- YYYYMMDD,如 "20250701"
- YYYYMMDDhhmmss,如 "20250701093000"
end_time (str): 结束时间,支持格式:
- YYYYMMDD,如 "20250731"
- YYYYMMDDhhmmss,如 "20250731150000"
count (int): 数据条数,-1表示全部数据
Returns:
None
"""
for stock_code in stock_codes:
for period in periods:
# xtdata.subscribe_quote(stock_code, period, start_time, end_time, count)
print(f"{LOG_PREFIXES['INFO']} 已订阅 {stock_code} 的 {period} 行情")
def on_data(datas):
"""
行情数据回调函数
Args:
datas (dict): 接收到的行情数据
"""
for stock_code in datas:
print(f"{LOG_PREFIXES['INFO']} 收到 {stock_code} 行情:", datas[stock_code])
def main():
"""
数据处理模型主程序入口函数 (批量周期模式) - 使用新的双层架构
执行完整的股票数据处理流程,支持批量下载多个周期的数据,
包括数据下载、格式化处理和MySQL数据库存储
主要执行步骤:
1. 初始化StockDataManager
2. 循环处理所有配置的数据周期
3. 对每个周期下载指定股票的历史数据
4. 对每个股票的数据进行格式化处理(时间转换、DataFrame化)
5. 将处理后的数据保存到MySQL数据库
6. 输出处理结果统计和信息
全局配置依赖:
- g_stock_code_list: 股票代码列表,如 ["601658.SH", "000001.SZ"]
- g_period_list: 数据周期列表,如 ["1m", "5m", "1d", "1w"]
- g_start_date: 开始日期,如 "20240101"
- g_end_date: 结束日期,如 "20241231"
Args:
无参数,使用全局配置变量
Returns:
None: 该函数不返回值,所有结果通过控制台输出
Side Effects:
- 在控制台输出详细的处理进度和结果
- 建立xtquant数据连接和MySQL数据库连接
- 为每个周期创建对应的数据库表
Raises:
KeyboardInterrupt: 用户手动中断程序执行
Exception: 数据下载、处理或数据库保存过程中的任何异常
Example:
>>> # 设置全局配置
>>> g_stock_code_list = ["601658.SH", "000001.SZ"]
>>> g_period_list = ["1m", "1d", "1w"]
>>> g_start_date = "20240101"
>>> g_end_date = "20240131"
>>>
>>> # 执行主程序
>>> main()
🎯 数据处理模型主程序 (批量周期模式)
📥 开始下载 3 个周期的历史数据...
✅ 成功处理所有周期数据
"""
data_manager = None
try:
print(f"{LOG_PREFIXES['INFO']} 数据处理启动...")
# 演示不同的时间格式选项
print(f"{LOG_PREFIXES['INFO']} xtquant 时间格式示例:")
print(f" - 完整时间格式: {format_time_for_xtquant(format_type='full')}")
print(f" - 日期格式: {format_time_for_xtquant(format_type='date')}")
print(f" - 交易开始时间: {format_time_for_xtquant(format_type='trading_start')}")
print(f" - 交易结束时间: {format_time_for_xtquant(format_type='trading_end')}")
# 根据数据周期推荐时间格式
print(f"{LOG_PREFIXES['INFO']} 推荐时间格式:")
print(" - 分钟级数据: YYYYMMDDhhmmss (具体到秒)")
print(" - 小时级数据: YYYYMMDDhhmmss 或 YYYYMMDD")
print(" - 日线及以上: YYYYMMDD (仅日期即可)")
# 初始化股票数据管理器
data_manager = get_stock_data_manager()
print(f"{LOG_PREFIXES['SUCCESS']} 数据管理器初始化完成")
# 统计结果
all_mysql_records = {}
total_periods_processed = 0
failed_periods = []
# 先订阅股票
subscribe_stocks_periods(g_stock_code_list, g_period_list, g_start_date, g_end_date)
# 处理每个周期
for current_period in g_period_list:
try:
print(f"\n{LOG_PREFIXES['DATABASE']} 处理周期: {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
)
# 修复DataFrame布尔判断问题 - 检查字典不为空
if stock_history_data and isinstance(stock_history_data, dict):
history_data.update(stock_history_data)
except Exception as e:
print(f"{LOG_PREFIXES['ERROR']} {stock_code} 下载失败: {e}")
continue
# 处理数据
processed_data = process_all_stocks(history_data, g_stock_code_list)
if not processed_data:
failed_periods.append(current_period)
continue
# 批量创建表
create_results = data_manager.create_tables_for_stocks(g_stock_code_list, current_period)
success_count = sum(create_results.values())
print(f"{LOG_PREFIXES['DATABASE']} 创建表: {success_count}/{len(g_stock_code_list)} 成功")
# 保存到数据库
mysql_records = save_all_to_mysql(processed_data, data_manager, current_period)
# 统计记录
for stock_code, count in mysql_records.items():
key = f"{stock_code}_{current_period}"
all_mysql_records[key] = count
total_periods_processed += 1
except Exception as e:
print(f"{LOG_PREFIXES['ERROR']} {current_period} 周期处理失败: {e}")
failed_periods.append(current_period)
continue
# 显示最终结果
if total_periods_processed > 0:
mysql_total = sum(all_mysql_records.values())
print(f"\n{LOG_PREFIXES['SUCCESS']} 处理完成: {total_periods_processed} 周期, {mysql_total} 条记录")
else:
print(f"\n{LOG_PREFIXES['ERROR']} 所有周期处理失败")
if failed_periods:
print(f"{LOG_PREFIXES['WARNING']} 失败周期: {', '.join(failed_periods)}")
except KeyboardInterrupt:
print(f"\n{LOG_PREFIXES['WARNING']} 用户中断")
except Exception as e:
print(f"\n{LOG_PREFIXES['ERROR']} 程序异常: {e}")
import traceback
traceback.print_exc()
finally:
if data_manager:
data_manager.close()
print(f"{LOG_PREFIXES['DATABASE']} 数据管理器已关闭")
# 程序不结束
#xtdata.run()
if __name__ == "__main__":
main()