feat: 实现按周期分表存储架构并修复时间戳问题
主要改进: 1. 架构重构 - 按周期分表存储 - 创建 table_utils.py 提供动态表名生成工具 - 支持7个周期的K线表: klines_1m, klines_5m, klines_15m, klines_30m, klines_60m, klines_1d, klines_1w - 支持6个指标库的分表: macd, kdj, rsi, boll, ma, ema (每个指标7个周期) - 动态生成49个周期表定义 2. 数据访问层更新 - 更新 data_provider.py 中10处SQL查询使用动态表名 - 更新 base_downloader.py 自动创建所有周期表 - 修改数据插入逻辑使用正确的周期表 3. 时间戳处理修复 - 修复 XtQuant 返回字符串时间戳(YYYYMMDDHHMMSS)解析问题 - 添加字符串转datetime支持: datetime.strptime(timestamp, '%Y%m%d%H%M%S') - 兼容 pandas Timestamp 和 datetime 对象 4. 配置更新 - 添加 XtQuant token 到 configs/global.yaml - 添加优化地址配置 5. 主程序完善 - 创建 src/main.py 实现完整的数据下载工作流 - 支持查询现有数据、下载历史数据、验证数据 - 错误处理和日志输出优化 测试结果: - 成功下载 5302 条1分钟K线数据 - 时间范围: 2025-12-01 09:30:00 ~ 2025-12-15 15:00:00 - 601658.SH (邮储银行): 2651条 - 159915.SZ (创业板ETF): 2651条 - 数据验证通过,时间戳正确
This commit is contained in:
parent
1c35db7752
commit
7e66691a44
@ -65,4 +65,11 @@ services:
|
|||||||
# QMT配置(公用部分)
|
# QMT配置(公用部分)
|
||||||
qmt:
|
qmt:
|
||||||
xtquant_path: "C:\\Program Files\\国金证券QMT交易端\\userdata_mini\\datadir"
|
xtquant_path: "C:\\Program Files\\国金证券QMT交易端\\userdata_mini\\datadir"
|
||||||
|
xtquant_token: "e83d8eec5226c0b4db4a1d40830e09e4ffe73e15" # XtQuant 数据接口 token(需要申请)
|
||||||
account_type: "STOCK" # STOCK-股票账户, CREDIT-信用账户
|
account_type: "STOCK" # STOCK-股票账户, CREDIT-信用账户
|
||||||
|
# XtQuant 优化地址(可选)
|
||||||
|
optimize_addresses:
|
||||||
|
- "115.231.218.73:55310"
|
||||||
|
- "115.231.218.79:55310"
|
||||||
|
- "218.16.123.11:55310"
|
||||||
|
- "218.16.123.27:55310"
|
||||||
|
|||||||
@ -134,16 +134,25 @@ class BaseDataDownloader(ABC):
|
|||||||
self.logger.warning(f"数据库 {self.database} 不存在,正在创建...")
|
self.logger.warning(f"数据库 {self.database} 不存在,正在创建...")
|
||||||
db_manager.create_database(self.database)
|
db_manager.create_database(self.database)
|
||||||
|
|
||||||
# 确保 klines 表存在
|
# 确保对应周期的 klines 表存在
|
||||||
klines_def = get_table_definition("klines")
|
from ...database_manager.table_utils import (
|
||||||
if not db_manager.table_exists(self.database, "klines"):
|
get_kline_table_name,
|
||||||
self.logger.warning("表 klines 不存在,正在创建...")
|
SUPPORTED_PERIODS,
|
||||||
db_manager.create_table(
|
)
|
||||||
database=self.database,
|
from ...database_manager.table_schemas import create_kline_table_definition
|
||||||
table_name=klines_def["name"],
|
|
||||||
columns=klines_def["columns"],
|
# 为所有支持的周期创建表(如果不存在)
|
||||||
indexes=klines_def["indexes"],
|
for period in SUPPORTED_PERIODS:
|
||||||
)
|
table_name = get_kline_table_name(period)
|
||||||
|
if not db_manager.table_exists(self.database, table_name):
|
||||||
|
self.logger.warning(f"表 {table_name} 不存在,正在创建...")
|
||||||
|
table_def = create_kline_table_definition(period)
|
||||||
|
db_manager.create_table(
|
||||||
|
database=self.database,
|
||||||
|
table_name=table_def["name"],
|
||||||
|
columns=table_def["columns"],
|
||||||
|
indexes=table_def["indexes"],
|
||||||
|
)
|
||||||
|
|
||||||
db_manager.close()
|
db_manager.close()
|
||||||
|
|
||||||
@ -292,12 +301,16 @@ class BaseDataDownloader(ABC):
|
|||||||
session = self.Session()
|
session = self.Session()
|
||||||
saved_count = 0
|
saved_count = 0
|
||||||
|
|
||||||
|
# 使用动态表名
|
||||||
|
from ...database_manager.table_utils import get_kline_table_name
|
||||||
|
|
||||||
|
table_name = get_kline_table_name(period)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
for kline in klines:
|
for kline in klines:
|
||||||
# 转换为数据库记录
|
# 转换为数据库记录(不再需要period字段)
|
||||||
record = {
|
record = {
|
||||||
"symbol": kline.symbol,
|
"symbol": kline.symbol,
|
||||||
"period": period,
|
|
||||||
"timestamp": kline.timestamp,
|
"timestamp": kline.timestamp,
|
||||||
"open": kline.open,
|
"open": kline.open,
|
||||||
"high": kline.high,
|
"high": kline.high,
|
||||||
@ -309,11 +322,11 @@ class BaseDataDownloader(ABC):
|
|||||||
|
|
||||||
# 使用 INSERT ... ON DUPLICATE KEY UPDATE 避免重复
|
# 使用 INSERT ... ON DUPLICATE KEY UPDATE 避免重复
|
||||||
# 这里使用原始 SQL
|
# 这里使用原始 SQL
|
||||||
sql = """
|
sql = f"""
|
||||||
INSERT INTO klines
|
INSERT INTO {table_name}
|
||||||
(symbol, period, timestamp, open, high, low, close, volume, amount)
|
(symbol, timestamp, open, high, low, close, volume, amount)
|
||||||
VALUES
|
VALUES
|
||||||
(:symbol, :period, :timestamp, :open, :high, :low, :close, :volume, :amount)
|
(:symbol, :timestamp, :open, :high, :low, :close, :volume, :amount)
|
||||||
ON DUPLICATE KEY UPDATE
|
ON DUPLICATE KEY UPDATE
|
||||||
open=VALUES(open), high=VALUES(high), low=VALUES(low),
|
open=VALUES(open), high=VALUES(high), low=VALUES(low),
|
||||||
close=VALUES(close), volume=VALUES(volume), amount=VALUES(amount)
|
close=VALUES(close), volume=VALUES(volume), amount=VALUES(amount)
|
||||||
|
|||||||
@ -72,9 +72,9 @@ class XtQuantDownloader(BaseDataDownloader):
|
|||||||
self, token: Optional[str], optimize_addresses: Optional[List[str]]
|
self, token: Optional[str], optimize_addresses: Optional[List[str]]
|
||||||
):
|
):
|
||||||
"""初始化 XtQuant 数据中心"""
|
"""初始化 XtQuant 数据中心"""
|
||||||
# 获取 token
|
# 获取 token(从配置文件 qmt.xtquant_token 读取)
|
||||||
if token is None:
|
if token is None:
|
||||||
token = self.config.get("xtquant.token")
|
token = self.config.get("qmt.xtquant_token")
|
||||||
if not token:
|
if not token:
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
"XtQuant token 未设置,请在配置文件中设置或通过参数传入"
|
"XtQuant token 未设置,请在配置文件中设置或通过参数传入"
|
||||||
@ -95,7 +95,7 @@ class XtQuantDownloader(BaseDataDownloader):
|
|||||||
|
|
||||||
# 设置优化地址
|
# 设置优化地址
|
||||||
if optimize_addresses is None:
|
if optimize_addresses is None:
|
||||||
optimize_addresses = self.config.get("xtquant.optimize_addresses", [])
|
optimize_addresses = self.config.get("qmt.optimize_addresses", [])
|
||||||
|
|
||||||
if optimize_addresses:
|
if optimize_addresses:
|
||||||
try:
|
try:
|
||||||
@ -165,6 +165,7 @@ class XtQuantDownloader(BaseDataDownloader):
|
|||||||
|
|
||||||
# 转换为 Kline 对象
|
# 转换为 Kline 对象
|
||||||
klines = []
|
klines = []
|
||||||
|
first_logged = False
|
||||||
for timestamp, row in df.iterrows():
|
for timestamp, row in df.iterrows():
|
||||||
# 跳过无效数据
|
# 跳过无效数据
|
||||||
if (
|
if (
|
||||||
@ -175,16 +176,41 @@ class XtQuantDownloader(BaseDataDownloader):
|
|||||||
):
|
):
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
# 将时间戳转换为 datetime
|
||||||
|
# XtQuant 返回的时间戳可能是字符串格式 "20251201093000"
|
||||||
|
# 或者是 pandas Timestamp 对象
|
||||||
|
from datetime import datetime as dt_class
|
||||||
|
|
||||||
|
if isinstance(timestamp, str):
|
||||||
|
# 字符串格式: YYYYMMDDHHMMSS
|
||||||
|
dt = dt_class.strptime(timestamp, "%Y%m%d%H%M%S")
|
||||||
|
elif hasattr(timestamp, "to_pydatetime"):
|
||||||
|
# pandas Timestamp 对象
|
||||||
|
dt = timestamp.to_pydatetime()
|
||||||
|
else:
|
||||||
|
# 已经是 datetime 对象
|
||||||
|
dt = timestamp
|
||||||
|
|
||||||
|
# 打印第一条数据的时间戳信息用于调试
|
||||||
|
if not first_logged:
|
||||||
|
self.logger.debug(
|
||||||
|
f"第一条时间戳 - 原始: {timestamp}, 类型: {type(timestamp)}"
|
||||||
|
)
|
||||||
|
self.logger.debug(f"第一条时间戳 - 转换后: {dt}, 类型: {type(dt)}")
|
||||||
|
first_logged = True
|
||||||
|
|
||||||
kline = Kline(
|
kline = Kline(
|
||||||
symbol=symbol,
|
symbol=symbol,
|
||||||
period=period, # 使用我们的标准周期格式
|
period=period, # 使用我们的标准周期格式
|
||||||
timestamp=timestamp,
|
timestamp=dt,
|
||||||
open=round(row["open"], 2),
|
open=round(row["open"], 2),
|
||||||
high=round(row["high"], 2),
|
high=round(row["high"], 2),
|
||||||
low=round(row["low"], 2),
|
low=round(row["low"], 2),
|
||||||
close=round(row["close"], 2),
|
close=round(row["close"], 2),
|
||||||
volume=int(row["volume"]),
|
volume=int(row["volume"]),
|
||||||
amount=round(row["amount"], 2) if row["amount"] > 0 else None,
|
amount=round(row["amount"], 2)
|
||||||
|
if row["amount"] and row["amount"] > 0
|
||||||
|
else 0.0, # 使用 0.0 替代 None
|
||||||
open_interest=0, # 股票没有持仓量
|
open_interest=0, # 股票没有持仓量
|
||||||
)
|
)
|
||||||
klines.append(kline)
|
klines.append(kline)
|
||||||
|
|||||||
@ -11,6 +11,7 @@ from sqlalchemy import create_engine, text
|
|||||||
from ..core.config import get_config
|
from ..core.config import get_config
|
||||||
from ..core.logger import get_logger
|
from ..core.logger import get_logger
|
||||||
from ..core.models import Kline
|
from ..core.models import Kline
|
||||||
|
from ..database_manager.table_utils import get_kline_table_name
|
||||||
|
|
||||||
|
|
||||||
logger = get_logger("DataProvider")
|
logger = get_logger("DataProvider")
|
||||||
@ -348,19 +349,19 @@ class DataProvider:
|
|||||||
)
|
)
|
||||||
engine = create_engine(connection_url)
|
engine = create_engine(connection_url)
|
||||||
|
|
||||||
|
# 使用动态表名
|
||||||
|
table_name = get_kline_table_name(period)
|
||||||
query = text(
|
query = text(
|
||||||
"""
|
f"""
|
||||||
SELECT * FROM klines
|
SELECT * FROM {table_name}
|
||||||
WHERE symbol = :symbol AND period = :period
|
WHERE symbol = :symbol
|
||||||
ORDER BY timestamp DESC
|
ORDER BY timestamp DESC
|
||||||
LIMIT 1
|
LIMIT 1
|
||||||
"""
|
"""
|
||||||
)
|
)
|
||||||
|
|
||||||
with engine.connect() as conn:
|
with engine.connect() as conn:
|
||||||
df = pd.read_sql(
|
df = pd.read_sql(query, conn, params={"symbol": symbol})
|
||||||
query, conn, params={"symbol": symbol, "period": period}
|
|
||||||
)
|
|
||||||
|
|
||||||
engine.dispose()
|
engine.dispose()
|
||||||
|
|
||||||
@ -414,12 +415,15 @@ class DataProvider:
|
|||||||
)
|
)
|
||||||
engine = create_engine(connection_url)
|
engine = create_engine(connection_url)
|
||||||
|
|
||||||
|
# 使用动态表名
|
||||||
|
table_name = get_kline_table_name(period)
|
||||||
|
|
||||||
# 构建查询
|
# 构建查询
|
||||||
if end_date:
|
if end_date:
|
||||||
query = text(
|
query = text(
|
||||||
"""
|
f"""
|
||||||
SELECT * FROM klines
|
SELECT * FROM {table_name}
|
||||||
WHERE symbol = :symbol AND period = :period
|
WHERE symbol = :symbol
|
||||||
AND timestamp <= :end_date
|
AND timestamp <= :end_date
|
||||||
ORDER BY timestamp DESC
|
ORDER BY timestamp DESC
|
||||||
LIMIT :count
|
LIMIT :count
|
||||||
@ -427,20 +431,19 @@ class DataProvider:
|
|||||||
)
|
)
|
||||||
params = {
|
params = {
|
||||||
"symbol": symbol,
|
"symbol": symbol,
|
||||||
"period": period,
|
|
||||||
"end_date": end_date,
|
"end_date": end_date,
|
||||||
"count": count,
|
"count": count,
|
||||||
}
|
}
|
||||||
else:
|
else:
|
||||||
query = text(
|
query = text(
|
||||||
"""
|
f"""
|
||||||
SELECT * FROM klines
|
SELECT * FROM {table_name}
|
||||||
WHERE symbol = :symbol AND period = :period
|
WHERE symbol = :symbol
|
||||||
ORDER BY timestamp DESC
|
ORDER BY timestamp DESC
|
||||||
LIMIT :count
|
LIMIT :count
|
||||||
"""
|
"""
|
||||||
)
|
)
|
||||||
params = {"symbol": symbol, "period": period, "count": count}
|
params = {"symbol": symbol, "count": count}
|
||||||
|
|
||||||
with engine.connect() as conn:
|
with engine.connect() as conn:
|
||||||
df = pd.read_sql(query, conn, params=params)
|
df = pd.read_sql(query, conn, params=params)
|
||||||
@ -525,14 +528,16 @@ class DataProvider:
|
|||||||
)
|
)
|
||||||
engine = create_engine(connection_url)
|
engine = create_engine(connection_url)
|
||||||
|
|
||||||
|
# 使用动态表名
|
||||||
|
table_name = get_kline_table_name(period)
|
||||||
query = text(
|
query = text(
|
||||||
"""
|
f"""
|
||||||
SELECT
|
SELECT
|
||||||
MIN(timestamp) as start_date,
|
MIN(timestamp) as start_date,
|
||||||
MAX(timestamp) as end_date,
|
MAX(timestamp) as end_date,
|
||||||
COUNT(*) as count
|
COUNT(*) as count
|
||||||
FROM klines
|
FROM {table_name}
|
||||||
WHERE symbol = :symbol AND period = :period
|
WHERE symbol = :symbol
|
||||||
AND timestamp BETWEEN :start_date AND :end_date
|
AND timestamp BETWEEN :start_date AND :end_date
|
||||||
"""
|
"""
|
||||||
)
|
)
|
||||||
@ -542,7 +547,6 @@ class DataProvider:
|
|||||||
query,
|
query,
|
||||||
{
|
{
|
||||||
"symbol": symbol,
|
"symbol": symbol,
|
||||||
"period": period,
|
|
||||||
"start_date": start_date,
|
"start_date": start_date,
|
||||||
"end_date": end_date,
|
"end_date": end_date,
|
||||||
},
|
},
|
||||||
@ -595,7 +599,9 @@ class DataProvider:
|
|||||||
)
|
)
|
||||||
engine = create_engine(connection_url)
|
engine = create_engine(connection_url)
|
||||||
|
|
||||||
query = text("SELECT DISTINCT symbol FROM klines ORDER BY symbol")
|
# 使用默认1d周期的表来查询symbol列表
|
||||||
|
table_name = get_kline_table_name("1d")
|
||||||
|
query = text(f"SELECT DISTINCT symbol FROM {table_name} ORDER BY symbol")
|
||||||
|
|
||||||
with engine.connect() as conn:
|
with engine.connect() as conn:
|
||||||
result = conn.execute(query)
|
result = conn.execute(query)
|
||||||
@ -629,6 +635,8 @@ class DataProvider:
|
|||||||
database = config.get("database.database")
|
database = config.get("database.database")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
from ..database_manager.table_utils import SUPPORTED_PERIODS
|
||||||
|
|
||||||
config = get_config()
|
config = get_config()
|
||||||
connection_url = (
|
connection_url = (
|
||||||
f"mysql+pymysql://{config.get('database.user')}:"
|
f"mysql+pymysql://{config.get('database.user')}:"
|
||||||
@ -638,13 +646,17 @@ class DataProvider:
|
|||||||
)
|
)
|
||||||
engine = create_engine(connection_url)
|
engine = create_engine(connection_url)
|
||||||
|
|
||||||
query = text(
|
# 检查每个周期的表中是否有该symbol的数据
|
||||||
"SELECT DISTINCT period FROM klines WHERE symbol = :symbol ORDER BY period"
|
periods = []
|
||||||
)
|
for period in SUPPORTED_PERIODS:
|
||||||
|
table_name = get_kline_table_name(period)
|
||||||
with engine.connect() as conn:
|
query = text(
|
||||||
result = conn.execute(query, {"symbol": symbol})
|
f"SELECT 1 FROM {table_name} WHERE symbol = :symbol LIMIT 1"
|
||||||
periods = [row[0] for row in result]
|
)
|
||||||
|
with engine.connect() as conn:
|
||||||
|
result = conn.execute(query, {"symbol": symbol}).fetchone()
|
||||||
|
if result:
|
||||||
|
periods.append(period)
|
||||||
|
|
||||||
engine.dispose()
|
engine.dispose()
|
||||||
return periods
|
return periods
|
||||||
@ -963,6 +975,9 @@ class DataProvider:
|
|||||||
columns_to_save = required_columns + optional_columns
|
columns_to_save = required_columns + optional_columns
|
||||||
df_to_save = df_copy[columns_to_save]
|
df_to_save = df_copy[columns_to_save]
|
||||||
|
|
||||||
|
# 使用动态表名
|
||||||
|
table_name = get_kline_table_name(period)
|
||||||
|
|
||||||
# 使用事务保存
|
# 使用事务保存
|
||||||
with engine.connect() as conn:
|
with engine.connect() as conn:
|
||||||
trans = conn.begin()
|
trans = conn.begin()
|
||||||
@ -970,36 +985,35 @@ class DataProvider:
|
|||||||
for _, row in df_to_save.iterrows():
|
for _, row in df_to_save.iterrows():
|
||||||
# 根据 on_duplicate 策略构建 SQL
|
# 根据 on_duplicate 策略构建 SQL
|
||||||
if on_duplicate == "update":
|
if on_duplicate == "update":
|
||||||
sql = text("""
|
sql = text(f"""
|
||||||
INSERT INTO klines
|
INSERT INTO {table_name}
|
||||||
(symbol, period, timestamp, open, high, low, close, volume, amount)
|
(symbol, timestamp, open, high, low, close, volume, amount)
|
||||||
VALUES
|
VALUES
|
||||||
(:symbol, :period, :timestamp, :open, :high, :low, :close, :volume, :amount)
|
(:symbol, :timestamp, :open, :high, :low, :close, :volume, :amount)
|
||||||
ON DUPLICATE KEY UPDATE
|
ON DUPLICATE KEY UPDATE
|
||||||
open=VALUES(open), high=VALUES(high), low=VALUES(low),
|
open=VALUES(open), high=VALUES(high), low=VALUES(low),
|
||||||
close=VALUES(close), volume=VALUES(volume), amount=VALUES(amount)
|
close=VALUES(close), volume=VALUES(volume), amount=VALUES(amount)
|
||||||
""")
|
""")
|
||||||
elif on_duplicate == "ignore":
|
elif on_duplicate == "ignore":
|
||||||
sql = text("""
|
sql = text(f"""
|
||||||
INSERT IGNORE INTO klines
|
INSERT IGNORE INTO {table_name}
|
||||||
(symbol, period, timestamp, open, high, low, close, volume, amount)
|
(symbol, timestamp, open, high, low, close, volume, amount)
|
||||||
VALUES
|
VALUES
|
||||||
(:symbol, :period, :timestamp, :open, :high, :low, :close, :volume, :amount)
|
(:symbol, :timestamp, :open, :high, :low, :close, :volume, :amount)
|
||||||
""")
|
""")
|
||||||
else: # replace
|
else: # replace
|
||||||
sql = text("""
|
sql = text(f"""
|
||||||
REPLACE INTO klines
|
REPLACE INTO {table_name}
|
||||||
(symbol, period, timestamp, open, high, low, close, volume, amount)
|
(symbol, timestamp, open, high, low, close, volume, amount)
|
||||||
VALUES
|
VALUES
|
||||||
(:symbol, :period, :timestamp, :open, :high, :low, :close, :volume, :amount)
|
(:symbol, :timestamp, :open, :high, :low, :close, :volume, :amount)
|
||||||
""")
|
""")
|
||||||
|
|
||||||
# 执行插入
|
# 执行插入(不再需要period参数)
|
||||||
conn.execute(
|
conn.execute(
|
||||||
sql,
|
sql,
|
||||||
{
|
{
|
||||||
"symbol": row["symbol"],
|
"symbol": row["symbol"],
|
||||||
"period": row["period"],
|
|
||||||
"timestamp": row["timestamp"],
|
"timestamp": row["timestamp"],
|
||||||
"open": float(row["open"]),
|
"open": float(row["open"]),
|
||||||
"high": float(row["high"]),
|
"high": float(row["high"]),
|
||||||
@ -1149,22 +1163,23 @@ class DataProvider:
|
|||||||
)
|
)
|
||||||
engine = create_engine(connection_url)
|
engine = create_engine(connection_url)
|
||||||
|
|
||||||
|
# 使用动态表名
|
||||||
|
table_name = get_kline_table_name(period)
|
||||||
|
|
||||||
# 构建批量查询 SQL
|
# 构建批量查询 SQL
|
||||||
placeholders = ", ".join([f":symbol{i}" for i in range(len(symbols))])
|
placeholders = ", ".join([f":symbol{i}" for i in range(len(symbols))])
|
||||||
query = text(
|
query = text(
|
||||||
f"""
|
f"""
|
||||||
SELECT * FROM klines
|
SELECT * FROM {table_name}
|
||||||
WHERE symbol IN ({placeholders})
|
WHERE symbol IN ({placeholders})
|
||||||
AND period = :period
|
|
||||||
AND timestamp BETWEEN :start_date AND :end_date
|
AND timestamp BETWEEN :start_date AND :end_date
|
||||||
ORDER BY symbol, timestamp
|
ORDER BY symbol, timestamp
|
||||||
"""
|
"""
|
||||||
)
|
)
|
||||||
|
|
||||||
# 构建参数
|
# 构建参数(不再需要period)
|
||||||
params = {
|
params = {
|
||||||
**{f"symbol{i}": symbol for i, symbol in enumerate(symbols)},
|
**{f"symbol{i}": symbol for i, symbol in enumerate(symbols)},
|
||||||
"period": period,
|
|
||||||
"start_date": start_date,
|
"start_date": start_date,
|
||||||
"end_date": end_date,
|
"end_date": end_date,
|
||||||
}
|
}
|
||||||
|
|||||||
@ -8,13 +8,14 @@ from .table_schemas import (
|
|||||||
get_table_definition,
|
get_table_definition,
|
||||||
get_all_table_names,
|
get_all_table_names,
|
||||||
TICK_TABLE,
|
TICK_TABLE,
|
||||||
KLINE_TABLE,
|
|
||||||
ORDER_TABLE,
|
ORDER_TABLE,
|
||||||
TRADE_TABLE,
|
TRADE_TABLE,
|
||||||
POSITION_TABLE,
|
POSITION_TABLE,
|
||||||
ACCOUNT_TABLE,
|
ACCOUNT_TABLE,
|
||||||
SIGNAL_TABLE,
|
SIGNAL_TABLE,
|
||||||
SYMBOL_TABLE,
|
SYMBOL_TABLE,
|
||||||
|
create_kline_table_definition,
|
||||||
|
create_indicator_table_definition,
|
||||||
)
|
)
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
@ -23,11 +24,12 @@ __all__ = [
|
|||||||
"get_table_definition",
|
"get_table_definition",
|
||||||
"get_all_table_names",
|
"get_all_table_names",
|
||||||
"TICK_TABLE",
|
"TICK_TABLE",
|
||||||
"KLINE_TABLE",
|
|
||||||
"ORDER_TABLE",
|
"ORDER_TABLE",
|
||||||
"TRADE_TABLE",
|
"TRADE_TABLE",
|
||||||
"POSITION_TABLE",
|
"POSITION_TABLE",
|
||||||
"ACCOUNT_TABLE",
|
"ACCOUNT_TABLE",
|
||||||
"SIGNAL_TABLE",
|
"SIGNAL_TABLE",
|
||||||
"SYMBOL_TABLE",
|
"SYMBOL_TABLE",
|
||||||
|
"create_kline_table_definition",
|
||||||
|
"create_indicator_table_definition",
|
||||||
]
|
]
|
||||||
|
|||||||
@ -1,9 +1,15 @@
|
|||||||
"""
|
"""
|
||||||
表结构定义
|
表结构定义
|
||||||
根据 core/models 中的对象定义数据库表结构
|
根据 core/models 中的对象定义数据库表结构
|
||||||
|
支持按周期分表存储(klines_1m, macd_1m 等)
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from typing import Dict, Any, List
|
from typing import Dict, Any, List
|
||||||
|
from .table_utils import (
|
||||||
|
get_all_kline_table_names,
|
||||||
|
get_all_indicator_table_names,
|
||||||
|
SUPPORTED_PERIODS,
|
||||||
|
)
|
||||||
|
|
||||||
# ==================== Tick 表 ====================
|
# ==================== Tick 表 ====================
|
||||||
TICK_TABLE = {
|
TICK_TABLE = {
|
||||||
@ -58,11 +64,70 @@ TICK_TABLE = {
|
|||||||
],
|
],
|
||||||
}
|
}
|
||||||
|
|
||||||
# ==================== Kline 表 ====================
|
|
||||||
KLINE_TABLE = {
|
# ==================== Kline 表(按周期分表)====================
|
||||||
"name": "klines",
|
def create_kline_table_definition(period: str) -> Dict[str, Any]:
|
||||||
"comment": "K线数据表",
|
"""
|
||||||
"columns": {
|
创建指定周期的K线表定义
|
||||||
|
|
||||||
|
Args:
|
||||||
|
period: 周期(1m/5m/60m/1d等)
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
表定义字典
|
||||||
|
"""
|
||||||
|
table_name = f"klines_{period}"
|
||||||
|
return {
|
||||||
|
"name": table_name,
|
||||||
|
"comment": f"K线数据表({period}周期)",
|
||||||
|
"columns": {
|
||||||
|
"id": {
|
||||||
|
"type": "Integer",
|
||||||
|
"primary_key": True,
|
||||||
|
"nullable": False,
|
||||||
|
"comment": "自增主键",
|
||||||
|
},
|
||||||
|
"symbol": {
|
||||||
|
"type": "String",
|
||||||
|
"length": 20,
|
||||||
|
"nullable": False,
|
||||||
|
"comment": "标的代码",
|
||||||
|
},
|
||||||
|
"timestamp": {"type": "DateTime", "nullable": False, "comment": "时间戳"},
|
||||||
|
"open": {"type": "Float", "nullable": False, "comment": "开盘价"},
|
||||||
|
"high": {"type": "Float", "nullable": False, "comment": "最高价"},
|
||||||
|
"low": {"type": "Float", "nullable": False, "comment": "最低价"},
|
||||||
|
"close": {"type": "Float", "nullable": False, "comment": "收盘价"},
|
||||||
|
"volume": {"type": "Integer", "nullable": False, "comment": "成交量"},
|
||||||
|
"amount": {"type": "Float", "nullable": False, "comment": "成交额"},
|
||||||
|
},
|
||||||
|
"indexes": [
|
||||||
|
{
|
||||||
|
"name": "idx_symbol_time",
|
||||||
|
"columns": ["symbol", "timestamp"],
|
||||||
|
"unique": True, # 同一股票同一时间只有一条记录
|
||||||
|
},
|
||||||
|
{"name": "idx_timestamp", "columns": ["timestamp"]},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ==================== 指标表(按周期分表)====================
|
||||||
|
def create_indicator_table_definition(indicator: str, period: str) -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
创建指定指标和周期的表定义
|
||||||
|
|
||||||
|
Args:
|
||||||
|
indicator: 指标名称(macd/kdj/rsi等)
|
||||||
|
period: 周期(1m/5m/60m/1d等)
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
表定义字典
|
||||||
|
"""
|
||||||
|
table_name = f"{indicator}_{period}"
|
||||||
|
|
||||||
|
# 基础列(所有指标表都有)
|
||||||
|
base_columns = {
|
||||||
"id": {
|
"id": {
|
||||||
"type": "Integer",
|
"type": "Integer",
|
||||||
"primary_key": True,
|
"primary_key": True,
|
||||||
@ -75,29 +140,60 @@ KLINE_TABLE = {
|
|||||||
"nullable": False,
|
"nullable": False,
|
||||||
"comment": "标的代码",
|
"comment": "标的代码",
|
||||||
},
|
},
|
||||||
"period": {
|
|
||||||
"type": "String",
|
|
||||||
"length": 10,
|
|
||||||
"nullable": False,
|
|
||||||
"comment": "周期(1m/5m/15m/30m/60m/1d/1w)",
|
|
||||||
},
|
|
||||||
"timestamp": {"type": "DateTime", "nullable": False, "comment": "时间戳"},
|
"timestamp": {"type": "DateTime", "nullable": False, "comment": "时间戳"},
|
||||||
"open": {"type": "Float", "nullable": False, "comment": "开盘价"},
|
}
|
||||||
"high": {"type": "Float", "nullable": False, "comment": "最高价"},
|
|
||||||
"low": {"type": "Float", "nullable": False, "comment": "最低价"},
|
# 根据不同指标添加特定列
|
||||||
"close": {"type": "Float", "nullable": False, "comment": "收盘价"},
|
indicator_columns = {}
|
||||||
"volume": {"type": "Integer", "nullable": False, "comment": "成交量"},
|
if indicator == "macd":
|
||||||
"amount": {"type": "Float", "nullable": False, "comment": "成交额"},
|
indicator_columns = {
|
||||||
},
|
"dif": {"type": "Float", "nullable": False, "comment": "DIF值"},
|
||||||
"indexes": [
|
"dea": {"type": "Float", "nullable": False, "comment": "DEA值"},
|
||||||
{
|
"macd": {"type": "Float", "nullable": False, "comment": "MACD柱值"},
|
||||||
"name": "idx_symbol_period_time",
|
}
|
||||||
"columns": ["symbol", "period", "timestamp"],
|
elif indicator == "kdj":
|
||||||
"unique": True,
|
indicator_columns = {
|
||||||
},
|
"k": {"type": "Float", "nullable": False, "comment": "K值"},
|
||||||
{"name": "idx_timestamp", "columns": ["timestamp"]},
|
"d": {"type": "Float", "nullable": False, "comment": "D值"},
|
||||||
],
|
"j": {"type": "Float", "nullable": False, "comment": "J值"},
|
||||||
}
|
}
|
||||||
|
elif indicator == "rsi":
|
||||||
|
indicator_columns = {
|
||||||
|
"rsi6": {"type": "Float", "nullable": True, "comment": "RSI6"},
|
||||||
|
"rsi12": {"type": "Float", "nullable": True, "comment": "RSI12"},
|
||||||
|
"rsi24": {"type": "Float", "nullable": True, "comment": "RSI24"},
|
||||||
|
}
|
||||||
|
elif indicator == "boll":
|
||||||
|
indicator_columns = {
|
||||||
|
"upper": {"type": "Float", "nullable": False, "comment": "上轨"},
|
||||||
|
"middle": {"type": "Float", "nullable": False, "comment": "中轨"},
|
||||||
|
"lower": {"type": "Float", "nullable": False, "comment": "下轨"},
|
||||||
|
}
|
||||||
|
elif indicator in ["ma", "ema"]:
|
||||||
|
indicator_columns = {
|
||||||
|
"ma5": {"type": "Float", "nullable": True, "comment": "5周期均线"},
|
||||||
|
"ma10": {"type": "Float", "nullable": True, "comment": "10周期均线"},
|
||||||
|
"ma20": {"type": "Float", "nullable": True, "comment": "20周期均线"},
|
||||||
|
"ma60": {"type": "Float", "nullable": True, "comment": "60周期均线"},
|
||||||
|
}
|
||||||
|
|
||||||
|
# 合并列定义
|
||||||
|
columns = {**base_columns, **indicator_columns}
|
||||||
|
|
||||||
|
return {
|
||||||
|
"name": table_name,
|
||||||
|
"comment": f"{indicator.upper()}指标表({period}周期)",
|
||||||
|
"columns": columns,
|
||||||
|
"indexes": [
|
||||||
|
{
|
||||||
|
"name": "idx_symbol_time",
|
||||||
|
"columns": ["symbol", "timestamp"],
|
||||||
|
"unique": True,
|
||||||
|
},
|
||||||
|
{"name": "idx_timestamp", "columns": ["timestamp"]},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
# ==================== Order 表 ====================
|
# ==================== Order 表 ====================
|
||||||
ORDER_TABLE = {
|
ORDER_TABLE = {
|
||||||
@ -483,9 +579,26 @@ SYMBOL_TABLE = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
# ==================== 所有表定义 ====================
|
# ==================== 所有表定义 ====================
|
||||||
|
# 动态生成所有周期的K线表
|
||||||
|
ALL_KLINE_TABLES = {
|
||||||
|
f"klines_{period}": create_kline_table_definition(period)
|
||||||
|
for period in SUPPORTED_PERIODS
|
||||||
|
}
|
||||||
|
|
||||||
|
# 动态生成所有指标表(所有周期×所有指标)
|
||||||
|
from .table_utils import SUPPORTED_INDICATORS
|
||||||
|
|
||||||
|
ALL_INDICATOR_TABLES = {
|
||||||
|
f"{indicator}_{period}": create_indicator_table_definition(indicator, period)
|
||||||
|
for indicator in SUPPORTED_INDICATORS
|
||||||
|
for period in SUPPORTED_PERIODS
|
||||||
|
}
|
||||||
|
|
||||||
|
# 合并所有表定义
|
||||||
ALL_TABLES = {
|
ALL_TABLES = {
|
||||||
|
**ALL_KLINE_TABLES,
|
||||||
|
**ALL_INDICATOR_TABLES,
|
||||||
"ticks": TICK_TABLE,
|
"ticks": TICK_TABLE,
|
||||||
"klines": KLINE_TABLE,
|
|
||||||
"orders": ORDER_TABLE,
|
"orders": ORDER_TABLE,
|
||||||
"trades": TRADE_TABLE,
|
"trades": TRADE_TABLE,
|
||||||
"positions": POSITION_TABLE,
|
"positions": POSITION_TABLE,
|
||||||
|
|||||||
106
src/database_manager/table_utils.py
Normal file
106
src/database_manager/table_utils.py
Normal file
@ -0,0 +1,106 @@
|
|||||||
|
"""
|
||||||
|
数据库表名工具函数
|
||||||
|
支持按周期分表存储
|
||||||
|
"""
|
||||||
|
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
# 支持的周期列表
|
||||||
|
SUPPORTED_PERIODS = ["1m", "5m", "15m", "30m", "60m", "1d", "1w"]
|
||||||
|
|
||||||
|
# 支持的指标列表
|
||||||
|
SUPPORTED_INDICATORS = ["macd", "kdj", "rsi", "boll", "ma", "ema"]
|
||||||
|
|
||||||
|
|
||||||
|
def get_kline_table_name(period: str) -> str:
|
||||||
|
"""
|
||||||
|
获取K线表名
|
||||||
|
|
||||||
|
Args:
|
||||||
|
period: 周期(1m/5m/60m/1d等)
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
表名(如 klines_1m)
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
>>> get_kline_table_name("1m")
|
||||||
|
'klines_1m'
|
||||||
|
>>> get_kline_table_name("1d")
|
||||||
|
'klines_1d'
|
||||||
|
"""
|
||||||
|
return f"klines_{period}"
|
||||||
|
|
||||||
|
|
||||||
|
def get_indicator_table_name(indicator: str, period: str) -> str:
|
||||||
|
"""
|
||||||
|
获取指标表名
|
||||||
|
|
||||||
|
Args:
|
||||||
|
indicator: 指标名称(macd/kdj/rsi等)
|
||||||
|
period: 周期(1m/5m/60m/1d等)
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
表名(如 macd_1m)
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
>>> get_indicator_table_name("macd", "1m")
|
||||||
|
'macd_1m'
|
||||||
|
>>> get_indicator_table_name("kdj", "1d")
|
||||||
|
'kdj_1d'
|
||||||
|
"""
|
||||||
|
return f"{indicator}_{period}"
|
||||||
|
|
||||||
|
|
||||||
|
def get_all_kline_table_names() -> List[str]:
|
||||||
|
"""
|
||||||
|
获取所有K线表名
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
所有周期的K线表名列表
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
>>> get_all_kline_table_names()
|
||||||
|
['klines_1m', 'klines_5m', 'klines_15m', 'klines_30m', 'klines_60m', 'klines_1d', 'klines_1w']
|
||||||
|
"""
|
||||||
|
return [get_kline_table_name(period) for period in SUPPORTED_PERIODS]
|
||||||
|
|
||||||
|
|
||||||
|
def get_all_indicator_table_names() -> List[str]:
|
||||||
|
"""
|
||||||
|
获取所有指标表名
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
所有指标和周期组合的表名列表
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
>>> tables = get_all_indicator_table_names()
|
||||||
|
>>> len(tables)
|
||||||
|
42 # 6个指标 x 7个周期
|
||||||
|
"""
|
||||||
|
tables = []
|
||||||
|
for indicator in SUPPORTED_INDICATORS:
|
||||||
|
for period in SUPPORTED_PERIODS:
|
||||||
|
tables.append(get_indicator_table_name(indicator, period))
|
||||||
|
return tables
|
||||||
|
|
||||||
|
|
||||||
|
def parse_table_name(table_name: str) -> tuple[str, str]:
|
||||||
|
"""
|
||||||
|
解析表名,提取数据类型和周期
|
||||||
|
|
||||||
|
Args:
|
||||||
|
table_name: 表名(如 klines_1m 或 macd_1d)
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
(数据类型, 周期) 元组
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
>>> parse_table_name("klines_1m")
|
||||||
|
('klines', '1m')
|
||||||
|
>>> parse_table_name("macd_1d")
|
||||||
|
('macd', '1d')
|
||||||
|
"""
|
||||||
|
parts = table_name.rsplit("_", 1)
|
||||||
|
if len(parts) == 2:
|
||||||
|
return parts[0], parts[1]
|
||||||
|
raise ValueError(f"无效的表名格式: {table_name}")
|
||||||
243
src/main.py
Normal file
243
src/main.py
Normal file
@ -0,0 +1,243 @@
|
|||||||
|
"""
|
||||||
|
QTrade 主程序
|
||||||
|
下载历史数据
|
||||||
|
"""
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
from .core.config import Config, set_config
|
||||||
|
from .core.logger import get_logger
|
||||||
|
from .data_provider import DataProvider
|
||||||
|
|
||||||
|
logger = get_logger("Main")
|
||||||
|
|
||||||
|
|
||||||
|
def download_historical_data():
|
||||||
|
"""下载历史数据"""
|
||||||
|
|
||||||
|
logger.info("=" * 60)
|
||||||
|
logger.info("开始下载历史数据")
|
||||||
|
logger.info("=" * 60)
|
||||||
|
|
||||||
|
# 股票列表:邮储银行、创业板ETF
|
||||||
|
symbols = [
|
||||||
|
"601658.SH", # 邮储银行
|
||||||
|
"159915.SZ", # 创业板ETF
|
||||||
|
]
|
||||||
|
|
||||||
|
# 时间范围:2025-12-01 到 2025-12-15
|
||||||
|
start_date = datetime(2025, 12, 1)
|
||||||
|
end_date = datetime(2025, 12, 15)
|
||||||
|
|
||||||
|
# 周期:1分钟数据
|
||||||
|
periods = ["1m"]
|
||||||
|
|
||||||
|
logger.info(f"\n下载配置:")
|
||||||
|
logger.info(f" 股票代码: {', '.join(symbols)}")
|
||||||
|
logger.info(f" 时间范围: {start_date.date()} ~ {end_date.date()}")
|
||||||
|
logger.info(f" 数据周期: {', '.join(periods)}")
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 使用 DataProvider 下载数据
|
||||||
|
result = DataProvider.download_klines(
|
||||||
|
symbols=symbols,
|
||||||
|
start_date=start_date,
|
||||||
|
end_date=end_date,
|
||||||
|
periods=periods,
|
||||||
|
downloader_type="xtquant",
|
||||||
|
)
|
||||||
|
|
||||||
|
logger.info(f"\n下载结果:")
|
||||||
|
logger.info(f" 总股票数: {result['total_symbols']}")
|
||||||
|
logger.info(f" 总周期数: {result['total_periods']}")
|
||||||
|
logger.info(f" 成功数量: {result['success_count']}")
|
||||||
|
logger.info(f" 失败数量: {result['failed_count']}")
|
||||||
|
logger.info(f" 总记录数: {result['total_records']}")
|
||||||
|
|
||||||
|
# 显示详细信息
|
||||||
|
if result["details"]:
|
||||||
|
logger.info(f"\n详细信息:")
|
||||||
|
for detail in result["details"]:
|
||||||
|
status = "✓" if detail.get("success", False) else "✗"
|
||||||
|
logger.info(
|
||||||
|
f" {status} {detail['symbol']} - {detail['period']}: "
|
||||||
|
f"{detail.get('records', 0)} 条 "
|
||||||
|
f"({detail.get('message', 'N/A')})"
|
||||||
|
)
|
||||||
|
|
||||||
|
logger.info(f"\n{'=' * 60}")
|
||||||
|
logger.info("历史数据下载完成")
|
||||||
|
logger.info(f"{'=' * 60}")
|
||||||
|
|
||||||
|
return result
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"下载失败: {e}", exc_info=True)
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
def verify_downloaded_data():
|
||||||
|
"""验证下载的数据"""
|
||||||
|
|
||||||
|
logger.info(f"\n{'=' * 60}")
|
||||||
|
logger.info("验证已下载的数据")
|
||||||
|
logger.info(f"{'=' * 60}")
|
||||||
|
|
||||||
|
symbols = ["601658.SH", "159915.SZ"]
|
||||||
|
start_date = datetime(2025, 12, 1)
|
||||||
|
end_date = datetime(2025, 12, 15)
|
||||||
|
period = "1m"
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 查询数据
|
||||||
|
klines = DataProvider.get_klines(
|
||||||
|
symbols=symbols, start_date=start_date, end_date=end_date, period=period
|
||||||
|
)
|
||||||
|
|
||||||
|
logger.info(f"\n数据验证结果:")
|
||||||
|
for symbol, df in klines.items():
|
||||||
|
if df.empty:
|
||||||
|
logger.warning(f" ✗ {symbol}: 无数据")
|
||||||
|
else:
|
||||||
|
logger.info(f" ✓ {symbol}: {len(df)} 条记录")
|
||||||
|
logger.info(f" 时间范围: {df.index[0]} ~ {df.index[-1]}")
|
||||||
|
logger.info(f" 数据示例:")
|
||||||
|
logger.info(f"{df.head(3).to_string()}")
|
||||||
|
|
||||||
|
return klines
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"验证失败: {e}", exc_info=True)
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
def query_existing_data():
|
||||||
|
"""查询已有数据并打印"""
|
||||||
|
|
||||||
|
logger.info("=" * 60)
|
||||||
|
logger.info("查询数据库中的历史数据")
|
||||||
|
logger.info("=" * 60)
|
||||||
|
|
||||||
|
# 股票列表
|
||||||
|
symbols = ["601658.SH", "159915.SZ"]
|
||||||
|
|
||||||
|
# 时间范围
|
||||||
|
start_date = datetime(2025, 12, 1)
|
||||||
|
end_date = datetime(2025, 12, 15)
|
||||||
|
|
||||||
|
# 周期
|
||||||
|
period = "1m"
|
||||||
|
|
||||||
|
logger.info(f"\n查询配置:")
|
||||||
|
logger.info(f" 股票代码: {', '.join(symbols)}")
|
||||||
|
logger.info(f" 时间范围: {start_date.date()} ~ {end_date.date()}")
|
||||||
|
logger.info(f" 数据周期: {period}")
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 使用 DataProvider 查询数据
|
||||||
|
klines = DataProvider.get_klines(
|
||||||
|
symbols=symbols, start_date=start_date, end_date=end_date, period=period
|
||||||
|
)
|
||||||
|
|
||||||
|
logger.info(f"\n查询结果:")
|
||||||
|
logger.info("=" * 60)
|
||||||
|
|
||||||
|
for symbol, df in klines.items():
|
||||||
|
if df.empty:
|
||||||
|
logger.warning(f"\n{symbol}: 无数据")
|
||||||
|
else:
|
||||||
|
logger.info(f"\n{symbol}:")
|
||||||
|
logger.info(f" 数据条数: {len(df)} 条")
|
||||||
|
logger.info(f" 时间范围: {df.index[0]} ~ {df.index[-1]}")
|
||||||
|
logger.info(f" 数据列: {', '.join(df.columns.tolist())}")
|
||||||
|
logger.info(f"\n 前5条数据:")
|
||||||
|
logger.info(f"\n{df.head(5).to_string()}")
|
||||||
|
logger.info(f"\n 后5条数据:")
|
||||||
|
logger.info(f"\n{df.tail(5).to_string()}")
|
||||||
|
|
||||||
|
# 统计信息
|
||||||
|
logger.info(f"\n 统计信息:")
|
||||||
|
logger.info(
|
||||||
|
f" 开盘价: {df['open'].min():.2f} ~ {df['open'].max():.2f}"
|
||||||
|
)
|
||||||
|
logger.info(
|
||||||
|
f" 最高价: {df['high'].min():.2f} ~ {df['high'].max():.2f}"
|
||||||
|
)
|
||||||
|
logger.info(
|
||||||
|
f" 最低价: {df['low'].min():.2f} ~ {df['low'].max():.2f}"
|
||||||
|
)
|
||||||
|
logger.info(
|
||||||
|
f" 收盘价: {df['close'].min():.2f} ~ {df['close'].max():.2f}"
|
||||||
|
)
|
||||||
|
logger.info(f" 成交量: {df['volume'].sum():,.0f}")
|
||||||
|
|
||||||
|
logger.info("\n" + "=" * 60)
|
||||||
|
return klines
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"查询失败: {e}", exc_info=True)
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
"""主函数"""
|
||||||
|
|
||||||
|
# 初始化配置(使用回测环境)
|
||||||
|
logger.info("初始化配置...")
|
||||||
|
config = Config()
|
||||||
|
config.load_with_global("configs/backtest.yaml")
|
||||||
|
set_config(config)
|
||||||
|
logger.info(f"✓ 配置加载完成: {config.get('app.name')}")
|
||||||
|
|
||||||
|
# 第一步:尝试查询已有数据(如果表不存在会报错,直接跳到下载)
|
||||||
|
logger.info("\n" + "=" * 60)
|
||||||
|
logger.info("第一步:查询数据库中的现有数据")
|
||||||
|
logger.info("=" * 60)
|
||||||
|
|
||||||
|
klines = {}
|
||||||
|
need_download = True
|
||||||
|
|
||||||
|
try:
|
||||||
|
klines = query_existing_data()
|
||||||
|
# 检查是否需要下载数据
|
||||||
|
need_download = any(df.empty for df in klines.values())
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"查询失败(表可能不存在),直接进入下载流程: {e}")
|
||||||
|
need_download = True
|
||||||
|
|
||||||
|
if need_download:
|
||||||
|
# 第二步:检查 token 并下载数据
|
||||||
|
logger.info("\n" + "=" * 60)
|
||||||
|
logger.info("第二步:下载历史数据")
|
||||||
|
logger.info("=" * 60)
|
||||||
|
|
||||||
|
token = config.get("qmt.xtquant_token")
|
||||||
|
if not token:
|
||||||
|
logger.error("\n" + "=" * 60)
|
||||||
|
logger.error("XtQuant token 未配置!")
|
||||||
|
logger.error("=" * 60)
|
||||||
|
logger.error("\n请按以下步骤配置:")
|
||||||
|
logger.error("1. 打开 configs/global.yaml 文件")
|
||||||
|
logger.error("2. 在 qmt 配置节点下设置 xtquant_token")
|
||||||
|
logger.error("3. 如果还没有 token,请访问 XtQuant 官网申请")
|
||||||
|
logger.error("\n示例配置:")
|
||||||
|
logger.error("qmt:")
|
||||||
|
logger.error(' xtquant_token: "your_token_here"')
|
||||||
|
logger.error("\n" + "=" * 60)
|
||||||
|
return
|
||||||
|
|
||||||
|
# 下载数据
|
||||||
|
download_historical_data()
|
||||||
|
|
||||||
|
# 第三步:验证下载的数据
|
||||||
|
logger.info("\n" + "=" * 60)
|
||||||
|
logger.info("第三步:验证下载的数据")
|
||||||
|
logger.info("=" * 60)
|
||||||
|
verify_downloaded_data()
|
||||||
|
else:
|
||||||
|
logger.info("\n✓ 数据库中已有完整数据,无需下载")
|
||||||
|
|
||||||
|
logger.info("\n✓ 所有任务完成!")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@ -23,21 +23,25 @@ os.environ["CONFIG_FILE"] = "configs/backtest.yaml"
|
|||||||
|
|
||||||
from src.data_provider import XtQuantDownloader # noqa: E402
|
from src.data_provider import XtQuantDownloader # noqa: E402
|
||||||
from src.database_manager import DatabaseManager # noqa: E402
|
from src.database_manager import DatabaseManager # noqa: E402
|
||||||
|
from src.core.config import Config, set_config # noqa: E402
|
||||||
|
|
||||||
print("=" * 70)
|
print("=" * 70)
|
||||||
print("测试 XtQuant 数据下载器")
|
print("测试 XtQuant 数据下载器")
|
||||||
print("=" * 70)
|
print("=" * 70)
|
||||||
|
|
||||||
# XtQuant Token
|
# 初始化配置
|
||||||
token = "e83d8eec5226c0b4db4a1d40830e09e4ffe73e15"
|
config = Config()
|
||||||
|
config.load_with_global("configs/backtest.yaml")
|
||||||
|
set_config(config)
|
||||||
|
|
||||||
# 优化地址
|
# XtQuant Token(从配置文件读取)
|
||||||
optimize_addresses = [
|
token = config.get("qmt.xtquant_token")
|
||||||
"115.231.218.73:55310",
|
if not token:
|
||||||
"115.231.218.79:55310",
|
print("错误: 请在 configs/global.yaml 中配置 qmt.xtquant_token")
|
||||||
"218.16.123.11:55310",
|
sys.exit(1)
|
||||||
"218.16.123.27:55310",
|
|
||||||
]
|
# 优化地址(从配置文件读取)
|
||||||
|
optimize_addresses = config.get("qmt.optimize_addresses", [])
|
||||||
|
|
||||||
# 测试1: 初始化下载器
|
# 测试1: 初始化下载器
|
||||||
print("\n测试1: 初始化 XtQuant 下载器")
|
print("\n测试1: 初始化 XtQuant 下载器")
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user