Spaces:
Sleeping
Sleeping
File size: 7,450 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 | """
数据加载模块(5分钟单一数据源架构)
支持三种数据源:
- local: 本地 parquet 文件或目录
- r2: 从 Cloudflare R2 下载 a_share_5m.parquet 到本地缓存
- huggingface: 从 Hugging Face Dataset 下载分区 parquet
通过 ParquetStore 用 DuckDB 磁盘数据库查询。
"""
import os
import logging
import config
from parquet_store import ParquetStore
logger = logging.getLogger(__name__)
def _ensure_r2_cache(
account_id: str,
access_key_id: str,
secret_access_key: str,
bucket_name: str,
prefix: str = "kline/",
data_file: str = "a_share_5m.parquet",
force_check: bool = False,
) -> tuple[str | None, bool]:
"""
确保 R2 文件已缓存到本地,返回 (本地缓存路径, 是否有新下载)。
- force_check=False(默认,启动时):本地缓存存在就直接用,不访问 R2
- force_check=True(定时刷新时):检查远程文件大小,按需下载
"""
from pathlib import Path
cache_dir = Path.home() / ".cache" / "ai-quant-factor"
cache_dir.mkdir(parents=True, exist_ok=True)
cache_file = str(cache_dir / data_file)
# 启动时:本地缓存存在就直接用,不访问 R2
if os.path.exists(cache_file) and not force_check:
local_size = os.path.getsize(cache_file)
logger.info(f"使用本地缓存(跳过 R2 检查): {cache_file} ({local_size / (1024*1024):.1f} MB)")
return cache_file, False
# 以下仅在 force_check=True 或本地无缓存时执行
import boto3
from boto3.s3.transfer import TransferConfig
endpoint = f"https://{account_id}.r2.cloudflarestorage.com"
s3 = boto3.client(
"s3",
endpoint_url=endpoint,
aws_access_key_id=access_key_id,
aws_secret_access_key=secret_access_key,
region_name="auto",
)
r2_key = f"{prefix}{data_file}"
need_download = True
if os.path.exists(cache_file):
local_size = os.path.getsize(cache_file)
try:
head = s3.head_object(Bucket=bucket_name, Key=r2_key)
remote_size = head["ContentLength"]
if local_size == remote_size:
logger.info(f"缓存与远程一致,无需下载: {cache_file} ({local_size / (1024*1024):.1f} MB)")
need_download = False
else:
logger.info(f"缓存大小不匹配 (本地 {local_size} vs 远程 {remote_size}),重新下载")
except Exception as e:
logger.warning(f"无法检查远程文件: {e},跳过刷新")
return cache_file, False
else:
logger.info("本地无缓存,首次下载")
if need_download:
logger.info(f"正在从 R2 下载 {r2_key} ...")
try:
transfer_config = TransferConfig(
multipart_threshold=1024 * 1024 * 1024,
multipart_chunksize=256 * 1024 * 1024, # 256MB/chunk,减少 R2 B类操作次数
)
s3.download_file(bucket_name, r2_key, cache_file, Config=transfer_config)
except Exception as e:
logger.error(f"R2 下载失败: {e}")
if os.path.exists(cache_file):
logger.warning("下载失败,降级使用旧缓存")
return cache_file, False
return None, False
file_size_mb = os.path.getsize(cache_file) / (1024 * 1024)
logger.info(f"下载完成: {file_size_mb:.1f} MB")
return cache_file, need_download
def get_parquet_store_from_r2(
account_id: str,
access_key_id: str,
secret_access_key: str,
bucket_name: str,
prefix: str = "kline/",
data_file: str = "a_share_5m.parquet",
force_check: bool = False,
) -> ParquetStore | None:
"""
从 R2 下载 parquet 到本地缓存,返回 ParquetStore。
force_check=False 时不访问 R2(启动用),True 时检查远程更新(刷新用)。
parquet 有更新时自动重建 .duckdb 磁盘数据库。
"""
cache_file, downloaded = _ensure_r2_cache(
account_id, access_key_id, secret_access_key,
bucket_name, prefix, data_file,
force_check=force_check,
)
if not cache_file:
return None
store = ParquetStore(cache_file, memory_limit=config.DUCKDB_MEMORY_LIMIT)
if downloaded:
store.rebuild(cache_file)
else:
store.load()
return store
def get_parquet_store_local(data_path: str) -> ParquetStore | None:
"""
从本地路径创建 ParquetStore。
data_path 可以是单个 parquet 文件或包含 parquet 分片的目录。
"""
from pathlib import Path
p = Path(data_path)
if not p.exists():
logger.error(f"本地数据路径不存在: {data_path}")
return None
if p.is_dir():
files = list(p.glob("*.parquet"))
if not files:
logger.error(f"目录下无 parquet 文件: {data_path}")
return None
if len(files) == 1:
parquet_path = str(files[0])
else:
logger.info(f"从本地目录加载 {len(files)} 个分片...")
parquet_path = str(p / "*.parquet")
else:
parquet_path = str(p)
store = ParquetStore(parquet_path, memory_limit=config.DUCKDB_MEMORY_LIMIT)
store.load()
return store
def get_parquet_store_from_hf(
repo_id: str,
token: str = "",
force_check: bool = False,
) -> ParquetStore | None:
"""
从 Hugging Face Dataset 下载分区 parquet,返回 ParquetStore。
分区格式: data/stock_code=sh.600000/data.parquet
使用 snapshot_download 自带增量缓存(ETag 检查)。
- force_check=False(启动):优先使用本地缓存,无缓存时才下载
- force_check=True(刷新):检查远程是否有更新
"""
from huggingface_hub import snapshot_download
logger.info(f"正在从 Hugging Face 获取数据: {repo_id} (force_check={force_check})")
try:
kwargs = {
"repo_id": repo_id,
"repo_type": "dataset",
"allow_patterns": "data/stock_code=*/data.parquet",
}
if token:
kwargs["token"] = token
if not force_check:
# 启动时尝试只用本地缓存
try:
local_dir = snapshot_download(**kwargs, local_files_only=True)
logger.info(f"使用本地 HF 缓存: {local_dir}")
except FileNotFoundError:
# 本地无缓存,必须下载
logger.info("本地无 HF 缓存,首次下载...")
local_dir = snapshot_download(**kwargs)
else:
# 刷新时检查远程更新
local_dir = snapshot_download(**kwargs)
except Exception as e:
logger.error(f"HF Dataset 下载失败: {e}")
return None
# 构造 glob 路径
parquet_pattern = os.path.join(local_dir, "data", "stock_code=*", "data.parquet")
parquet_pattern = parquet_pattern.replace("\\", "/")
logger.info(f"HF 数据路径: {parquet_pattern}")
store = ParquetStore(parquet_pattern, memory_limit=config.DUCKDB_MEMORY_LIMIT)
# 检查 .duckdb 是否需要重建
if not os.path.exists(store._db_path):
store.load() # 首次:会触发 _build_database
elif force_check:
store.rebuild(parquet_pattern) # 刷新时重建
else:
store.load() # 正常加载
return store
|