优化时间格式配置和枚举命名
- 修改 TimeFrame 枚举:HOUR_1 -> MINUTE_60,保持命名一致性 - 更新时间格式支持 xtquant API 要求的 YYYYMMDDhhmmss 格式 - 添加时间格式化工具函数 format_time_for_xtquant() - 完善实时行情订阅功能 - 更新所有相关引用和配置
This commit is contained in:
parent
05c1cc0a6d
commit
6bb33b3720
@ -31,7 +31,7 @@ class TimeFrame(Enum):
|
||||
MINUTE_5 = "5m" # 5分钟
|
||||
MINUTE_15 = "15m" # 15分钟
|
||||
MINUTE_30 = "30m" # 30分钟
|
||||
HOUR_1 = "60m" # 1小时 (别名:1h)
|
||||
MINUTE_60 = "60m" # 60分钟 (1小时)
|
||||
DAILY = "1d" # 日线
|
||||
WEEKLY = "1w" # 周线
|
||||
MONTHLY = "1M" # 月线
|
||||
|
||||
@ -21,14 +21,25 @@ g_stock_code_list = [
|
||||
normalize_stock_code("510310.SH"),
|
||||
normalize_stock_code("601398.SH")
|
||||
] # 标准化后的股票代码
|
||||
g_start_date = "20240101" # 开始日期
|
||||
|
||||
# 手动设置结束日期,而不依赖系统当前日期
|
||||
# 选项1: 使用当前日期 (可能受到数据源更新延迟影响)
|
||||
g_end_date = datetime.datetime.now().strftime("%Y%m%d")
|
||||
# 调整时间范围到最近的一个月,避免跨度过大导致数据获取问题
|
||||
# xtquant API 要求:支持格式 YYYYMMDD 或 YYYYMMDDhhmmss
|
||||
# 若取某日全量历史数据,时间需要具体到秒,如 "20200427093000"
|
||||
|
||||
# 选项2: 手动指定确切日期 (推荐用于调试)
|
||||
#g_end_date = "20250728" # 手动指定到7月28日
|
||||
# 开始时间:7月1日 09:30:00 (交易开始时间)
|
||||
g_start_date = "20250701093000"
|
||||
|
||||
# 结束时间选项
|
||||
# 选项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}")
|
||||
|
||||
@ -41,7 +52,7 @@ g_save_csv = False # 默认不保存CSV文件,如需保存请设置为True
|
||||
# 说明:控制数据保存策略,提升插入性能
|
||||
# - "incremental": 增量模式,只插入新数据,跳过已存在的记录 (推荐)
|
||||
# - "replace": 替换模式,清空表后重新插入所有数据 (适用于数据修正)
|
||||
g_insert_mode = "incremental" # 默认使用增量插入模式
|
||||
g_insert_mode = "incremental" # 恢复增量插入模式
|
||||
|
||||
|
||||
''''
|
||||
@ -62,8 +73,7 @@ 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.HOUR_1.value, # "60m" - 60分钟
|
||||
TimeFrame.MINUTE_60.value, # "60m" - 60分钟 (1小时)
|
||||
TimeFrame.DAILY.value # "1d" - 日线
|
||||
]
|
||||
|
||||
@ -83,6 +93,74 @@ g_period_list = [
|
||||
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): 开始日期,如 "20250701"
|
||||
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):
|
||||
"""
|
||||
将时间戳转换为格式化时间字符串
|
||||
@ -385,6 +463,43 @@ def process_all_stocks(history_data, stock_codes):
|
||||
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():
|
||||
"""
|
||||
数据处理模型主程序入口函数 (批量周期模式) - 使用新的双层架构
|
||||
@ -440,6 +555,19 @@ def main():
|
||||
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']} 数据管理器初始化完成")
|
||||
@ -449,6 +577,9 @@ def main():
|
||||
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:
|
||||
@ -516,5 +647,9 @@ def main():
|
||||
print(f"{LOG_PREFIXES['DATABASE']} 数据管理器已关闭")
|
||||
|
||||
|
||||
# 程序不结束
|
||||
#xtdata.run()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@ -12,7 +12,7 @@ from common import (
|
||||
)
|
||||
|
||||
import logging
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@ -6,18 +6,18 @@
|
||||
|
||||
import pandas as pd
|
||||
import logging
|
||||
from typing import Dict, List, Optional, Union, Any
|
||||
from typing import Dict, List, Optional, Any
|
||||
from decimal import Decimal
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import datetime
|
||||
|
||||
# 导入底层依赖
|
||||
from database_manager import get_database_manager
|
||||
from stock_models import create_stock_kline_model, StockKlineBase
|
||||
from stock_models import create_stock_kline_model
|
||||
|
||||
# 导入公共配置
|
||||
from common import (
|
||||
normalize_stock_code, get_table_name, get_cache_key,
|
||||
validate_kline_data, LOG_PREFIXES, KLINE_COLUMNS, TimeFrame
|
||||
normalize_stock_code, get_table_name,
|
||||
validate_kline_data, LOG_PREFIXES
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@ -1,63 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
测试重构后的K线查看器
|
||||
验证新的双层架构是否正常工作
|
||||
"""
|
||||
|
||||
from stock_kline_viewer import StockKlineViewer
|
||||
from technical_indicators import IndicatorParams
|
||||
from common import LOG_PREFIXES
|
||||
|
||||
def test_kline_viewer():
|
||||
"""测试K线查看器的基本功能"""
|
||||
print(f"{LOG_PREFIXES['INFO']} 开始测试重构后的K线查看器...")
|
||||
|
||||
try:
|
||||
# 创建K线查看器
|
||||
viewer = StockKlineViewer()
|
||||
|
||||
if viewer.data_manager is None:
|
||||
print(f"{LOG_PREFIXES['ERROR']} 数据管理器初始化失败")
|
||||
return False
|
||||
|
||||
print(f"{LOG_PREFIXES['SUCCESS']} K线查看器初始化成功")
|
||||
|
||||
# 测试获取价格信息
|
||||
stock_code = "601658.SH"
|
||||
period = "1d"
|
||||
|
||||
price_info = viewer.get_price_info(stock_code, period)
|
||||
if price_info:
|
||||
print(f"{LOG_PREFIXES['SUCCESS']} 价格信息获取成功:")
|
||||
print(f" 最新价格: {price_info['latest_price']:.4f}")
|
||||
print(f" 涨跌幅: {price_info['change_pct']:.2f}%")
|
||||
print(f" 数据范围: {price_info['date_range']}")
|
||||
|
||||
# 测试读取数据
|
||||
df = viewer.data_manager.read_stock_data(stock_code, period, limit=10)
|
||||
if not df.empty:
|
||||
print(f"{LOG_PREFIXES['SUCCESS']} 数据读取成功: {len(df)} 条记录")
|
||||
print(f" 最新收盘价: {df['close'].iloc[-1]:.4f}")
|
||||
|
||||
# 测试技术指标计算
|
||||
if len(df) >= 60: # 确保有足够的数据计算60日均线
|
||||
params = IndicatorParams(ma_periods=[5, 10, 20])
|
||||
indicators = viewer.calculate_indicators(df, params)
|
||||
if indicators:
|
||||
print(f"{LOG_PREFIXES['SUCCESS']} 技术指标计算成功:")
|
||||
if 'ma' in indicators:
|
||||
print(f" 计算了 {len(indicators['ma'])} 条移动平均线")
|
||||
if 'macd' in indicators:
|
||||
print(" MACD指标计算完成")
|
||||
|
||||
print(f"{LOG_PREFIXES['SUCCESS']} 所有测试通过!新的双层架构工作正常")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
print(f"{LOG_PREFIXES['ERROR']} 测试失败: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return False
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_kline_viewer()
|
||||
Loading…
Reference in New Issue
Block a user