Spaces:
Sleeping
Sleeping
Download parquet_store.py from zbgool/quant-engine: direct link, hf CLI and curl.
- Browser
- Download file 10.2 kB
-
https://huggingface.co/spaces/zbgool/quant-engine/resolve/main/parquet_store.py
- Command line
-
hf download hf://spaces/zbgool/quant-engine/parquet_store.py
-
curl -L -o parquet_store.py https://huggingface.co/spaces/zbgool/quant-engine/resolve/main/parquet_store.py
10.2 kB
| """ | |
| 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] | |
| 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) | |
| 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 | |