Spaces:
Sleeping
Sleeping
File size: 10,205 Bytes
c68f3b9 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 | """
ParquetStore — DuckDB 磁盘数据库模式。
首次启动:parquet → .duckdb 磁盘数据库(一次性转换)。
后续查询:read_only=True 连接磁盘数据库,线程安全,支持并发。
通过 DUCKDB_MEMORY_LIMIT 环境变量自适应不同服务器规格:
- 16G 服务器(默认 3GB):分批导入,跳过索引
- 32G 服务器(设 10GB):一步导入,建索引,查询更快
"""
import logging
import os
import shutil
from collections.abc import Iterator
import duckdb
import numpy as np
import pandas as pd
logger = logging.getLogger(__name__)
OHLCV_COLUMNS = ("open", "high", "low", "close", "volume", "amount")
def _downcast_dtypes(df: pd.DataFrame) -> pd.DataFrame:
"""全列降为 float32 节省内存"""
for col in OHLCV_COLUMNS:
if col in df.columns:
df[col] = df[col].astype(np.float32)
return df
def _parse_datetime_index(df: pd.DataFrame) -> pd.DataFrame:
"""统一解析 datetime 列并设为 index"""
if "datetime" in df.columns:
df["datetime"] = pd.to_datetime(df["datetime"])
df.set_index("datetime", inplace=True)
elif "date" in df.columns and "time" in df.columns:
df["datetime"] = pd.to_datetime(
df["time"].str[:14], format="%Y%m%d%H%M%S"
)
df.set_index("datetime", inplace=True)
df.drop(columns=["date", "time"], errors="ignore", inplace=True)
elif "date" in df.columns:
df["date"] = pd.to_datetime(df["date"])
df.set_index("date", inplace=True)
return df
def _process_stock_df(df: pd.DataFrame) -> pd.DataFrame:
"""处理单只股票的 DataFrame:删 code、解析时间、降精度"""
df = df.drop(columns=["code"], errors="ignore")
df = _parse_datetime_index(df)
for col in OHLCV_COLUMNS:
if col in df.columns:
df[col] = pd.to_numeric(df[col], errors="coerce")
df = _downcast_dtypes(df)
df.sort_index(inplace=True)
return df
class ParquetStore:
"""DuckDB 磁盘数据库模式。
首次 load():parquet → .duckdb 磁盘数据库(一次性)。
查询:read_only=True(支持多线程并发读)。
memory_limit 控制 DuckDB 缓冲池大小,不会 OOM。
"""
def __init__(self, parquet_path: str, memory_limit: str = "3GB"):
self._parquet_path = parquet_path.replace("\\", "/")
self._db_path = self._derive_db_path(parquet_path)
self._memory_limit = memory_limit
self._codes: list[str] = []
# 检测是否为 hive 分区格式 (stock_code=xxx/data.parquet)
self._is_hive = "stock_code=" in self._parquet_path
# 保存分区基目录(用于 get_stock_data_direct)
self._base_dir: str | None = None
if self._is_hive:
# data/stock_code=*/data.parquet → data 目录的上级
parts = self._parquet_path.split("/stock_code=")
if parts:
self._base_dir = parts[0]
@staticmethod
def _cleanup_db_files(db_path: str):
"""删除 .duckdb 及其附属文件(.wal 等)"""
for suffix in ("", ".wal"):
f = db_path + suffix
if os.path.exists(f):
os.remove(f)
@staticmethod
def _derive_db_path(parquet_path: str) -> str:
"""从 parquet 路径推导 .duckdb 路径"""
p = parquet_path.replace("\\", "/")
# hive 分区路径: .../data/stock_code=*/data.parquet → .../stocks.duckdb
if "stock_code=" in p:
base = p.split("/stock_code=")[0]
# base 是 .../data 目录,.duckdb 放在其上级
parent = os.path.dirname(base)
return os.path.join(parent, "stocks.duckdb").replace("\\", "/")
# 通配符路径 (e.g. /dir/*.parquet → /dir/data.duckdb)
if "*" in p:
return os.path.join(os.path.dirname(p), "data.duckdb")
return p.rsplit(".", 1)[0] + ".duckdb"
def _connect_readonly(self) -> duckdb.DuckDBPyConnection:
"""只读连接磁盘数据库(线程安全,支持并发)"""
con = duckdb.connect(self._db_path, read_only=True)
con.execute(f"SET memory_limit='{self._memory_limit}'")
return con
def load(self):
"""首次:parquet → DuckDB 磁盘数据库;后续:直接读磁盘库"""
if not os.path.exists(self._db_path):
self._build_database()
con = self._connect_readonly()
try:
codes_df = con.execute(
"SELECT DISTINCT code FROM stocks ORDER BY code"
).fetchdf()
self._codes = codes_df["code"].tolist()
logger.info(f"ParquetStore 就绪: {len(self._codes)} 只标的(磁盘数据库模式)")
finally:
con.close()
def _build_database(self):
"""将 parquet 导入 DuckDB 磁盘数据库(通过 temp_directory 磁盘溢出控制内存)"""
logger.info(f"正在将 parquet 转为 DuckDB 磁盘数据库: {self._parquet_path} → {self._db_path}")
temp_dir = os.path.join(os.path.dirname(self._db_path), "duckdb_tmp").replace("\\", "/")
con = duckdb.connect(self._db_path)
try:
con.execute(f"SET memory_limit='{self._memory_limit}'")
con.execute(f"SET temp_directory='{temp_dir}'")
if self._is_hive:
parquet_ref = f"read_parquet('{self._parquet_path}', hive_partitioning=true)"
select_expr = f"SELECT stock_code AS code, * EXCLUDE(stock_code) FROM {parquet_ref}"
else:
parquet_ref = f"read_parquet('{self._parquet_path}')"
select_expr = f"SELECT * FROM {parquet_ref}"
logger.info(f"开始导入 (memory_limit={self._memory_limit}, temp_dir={temp_dir})...")
con.execute(f"CREATE TABLE stocks AS {select_expr}")
try:
con.execute("CREATE INDEX idx_stocks_code ON stocks(code)")
con.execute("CHECKPOINT")
logger.info("磁盘数据库创建完成(含索引)")
except Exception as e:
logger.warning(f"跳过索引创建(不影响功能): {e}")
logger.info("磁盘数据库创建完成(无索引)")
except Exception:
con.close()
self._cleanup_db_files(self._db_path)
raise
else:
try:
con.execute("CHECKPOINT")
except Exception:
pass
con.close()
wal_path = self._db_path + ".wal"
if os.path.exists(wal_path):
os.remove(wal_path)
logger.info("已清理残留 WAL 文件")
finally:
if os.path.exists(temp_dir):
shutil.rmtree(temp_dir, ignore_errors=True)
logger.info("已清理临时溢出目录")
def get_codes(self) -> list[str]:
return self._codes
def get_stock_data(self, code: str) -> pd.DataFrame:
"""查询单只股票数据(只读连接,线程安全)"""
con = self._connect_readonly()
try:
df = con.execute(
"SELECT * FROM stocks WHERE code = $1", [code]
).fetchdf()
finally:
con.close()
if df.empty:
return df
return _process_stock_df(df)
def iter_stocks_batched(
self, batch_size: int = 200, codes: list[str] | None = None,
) -> Iterator[tuple[str, pd.DataFrame, int, int]]:
"""分批迭代股票(只读连接,线程安全)。
codes: 指定要迭代的股票列表,None 表示全部。
每次 yield: (code, df_5m, batch_num, total_batches)
磁盘数据库 + code 索引 → 每批查询毫秒级。
"""
target_codes = codes if codes is not None else self._codes
total = len(target_codes)
total_batches = (total + batch_size - 1) // batch_size
con = self._connect_readonly()
try:
for batch_idx in range(total_batches):
start = batch_idx * batch_size
end = min(start + batch_size, total)
batch_codes = target_codes[start:end]
placeholders = ", ".join([f"${i+1}" for i in range(len(batch_codes))])
batch_df = con.execute(
f"SELECT * FROM stocks WHERE code IN ({placeholders})",
batch_codes,
).fetchdf()
if batch_df.empty:
continue
for code, group in batch_df.groupby("code"):
yield str(code), _process_stock_df(group.copy()), batch_idx + 1, total_batches
finally:
con.close()
def rebuild(self, new_parquet_path: str):
"""刷新数据:删除旧 .duckdb,重新从 parquet 构建"""
self._parquet_path = new_parquet_path.replace("\\", "/")
new_db_path = self._derive_db_path(new_parquet_path)
self._cleanup_db_files(new_db_path)
logger.info(f"已删除旧磁盘数据库: {new_db_path}")
self._db_path = new_db_path
self.load()
def __len__(self) -> int:
return len(self._codes)
def __bool__(self) -> bool:
return len(self._codes) > 0
def get_stock_data_direct(self, code: str) -> pd.DataFrame:
"""直接读取分区 parquet 文件,跳过 DuckDB(适用于单股查看场景)。
仅在 hive 分区模式下可用,否则 fallback 到 get_stock_data。
"""
if not self._is_hive or not self._base_dir:
return self.get_stock_data(code)
parquet_file = os.path.join(self._base_dir, f"stock_code={code}", "data.parquet")
parquet_file = parquet_file.replace("\\", "/")
if not os.path.exists(parquet_file):
return pd.DataFrame()
df = pd.read_parquet(parquet_file)
df = _parse_datetime_index(df)
for col in OHLCV_COLUMNS:
if col in df.columns:
df[col] = pd.to_numeric(df[col], errors="coerce")
df = _downcast_dtypes(df)
df.sort_index(inplace=True)
return df
|