jinjing-shared-data / scripts /factor_priors.py
cedwyh's picture
Upload scripts/factor_priors.py with huggingface_hub
eaddf2b verified
Raw
History Blame Contribute Delete
32.3 kB
#!/usr/bin/env python3
from __future__ import annotations
"""
factor_priors.py — PRISM-VQ A1: 13 经典截面先验因子计算模块
从 yfinance OHLCV、yfinance info、akshare 财务数据 计算 13 个经典截面因子。
每个因子输出统一格式:{"status": "ok"/"error", "value": <float or None>, "detail": "..."}
支持 --use-cache 模式:从 priors_cache/ 目录读取预下载的 OHLCV、info、financial 数据。
防泄露核心规则:
- compute_all_priors() 使用 df_ohlcv 切片确保只用到截止 date 的数据
- 财务数据用最近一个财报期的值
- yfinance info 是快照数据,只用在推理日期已知的信息
"""
import logging
import os
import re
import threading
import time
from functools import lru_cache
from pathlib import Path
import numpy as np
import pandas as pd
import yfinance as yf
logger = logging.getLogger(__name__)
# ── CSI 300 benchmark symbol ──
CACHE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "priors_cache")
# ── CSI 300 benchmark symbol (fallback 用) ──
BENCHMARK_SYMBOL = "000300.SS"
# ── Benchmark data cache (CSI 300 fallback) ──
_benchmark_close: pd.Series | None = None
_benchmark_ts: float = 0
BENCHMARK_CACHE_TTL = 3600 # 1 hour
# ── 全市场等权收益率缓存 ──
_market_returns_cache: pd.Series | None = None
_market_returns_ts: float = 0
MARKET_RETURNS_CACHE_TTL = 3600
def _to_yf(symbol: str) -> str:
"""Convert internal symbol (sh600000) to yfinance format (600000.SS)."""
if symbol.endswith(".SS") or symbol.endswith(".SZ"):
return symbol
if len(symbol) > 2:
prefix, code = symbol[:2], symbol[2:]
if prefix == "sh":
return f"{code}.SS"
elif prefix == "sz":
return f"{code}.SZ"
return symbol
# ===================================================================
# 缓存读取函数(新增)
# ===================================================================
def _get_cache_dir(symbol: str) -> str:
"""获取单个股票的缓存目录路径。"""
return os.path.join(CACHE_DIR, symbol)
def load_cached_ohlcv(symbol: str) -> pd.DataFrame | None:
"""从缓存读取 OHLCV 数据。
Args:
symbol: 股票代码 (e.g., "sh600000")
Returns:
DataFrame with columns [date, open, high, low, close, volume], 或 None
"""
path = os.path.join(_get_cache_dir(symbol), "ohlcv.parquet")
if not os.path.exists(path):
return None
try:
df = pd.read_parquet(path)
if df.empty:
return None
df["date"] = pd.to_datetime(df["date"])
return df
except Exception as e:
logger.warning(f"读取 OHLCV 缓存失败 [{symbol}]: {e}")
return None
def load_cached_info(symbol: str) -> dict[str, float | None] | None:
"""从缓存读取 yfinance info 字段。
Returns:
{field: value} 字典,或 None
"""
path = os.path.join(_get_cache_dir(symbol), "info.parquet")
if not os.path.exists(path):
return None
try:
df = pd.read_parquet(path)
if df.empty:
return None
record = df.iloc[0].to_dict()
# 过滤掉 symbol 列,只保留数值字段
return {k: v for k, v in record.items() if k != "symbol"}
except Exception as e:
logger.warning(f"读取 Info 缓存失败 [{symbol}]: {e}")
return None
def load_cached_financial(symbol: str) -> dict[str, float | None] | None:
"""从缓存读取 akshare 财务数据。
Returns:
{roe, gross_margin, asset_growth} 字典,或 None
"""
path = os.path.join(_get_cache_dir(symbol), "financial.parquet")
if not os.path.exists(path):
return None
try:
df = pd.read_parquet(path)
if df.empty:
return None
record = df.iloc[0].to_dict()
return {
"roe": record.get("roe"),
"gross_margin": record.get("gross_margin"),
"asset_growth": record.get("asset_growth"),
}
except Exception as e:
logger.warning(f"读取 Financial 缓存失败 [{symbol}]: {e}")
return None
def load_cached_market_returns() -> pd.Series | None:
"""从缓存读取全市场等权日收益率序列。
Returns:
pd.Series with datetime index and market_return values, or None
"""
global _market_returns_cache, _market_returns_ts
now = time.time()
if _market_returns_cache is not None and (now - _market_returns_ts) < MARKET_RETURNS_CACHE_TTL:
return _market_returns_cache
path = os.path.join(CACHE_DIR, "market_returns.parquet")
if not os.path.exists(path):
return None
try:
df = pd.read_parquet(path)
if df.empty or "market_return" not in df.columns:
return None
series = df["market_return"].sort_index()
series.index = pd.to_datetime(series.index)
_market_returns_cache = series
_market_returns_ts = now
return series
except Exception as e:
logger.warning(f"读取市场收益率缓存失败: {e}")
return None
# ===================================================================
# 基准收益率(保留 CSI 300 作为后备)
# ===================================================================
def _get_benchmark_returns(end_date: pd.Timestamp, max_periods: int = 504) -> np.ndarray:
"""Get CSI 300 daily returns up to end_date (防数据泄露), cached for TTL.
Uses yfinance first, falls back to akshare for A-share indices.
"""
global _benchmark_close, _benchmark_ts
now = time.time()
if _benchmark_close is None or (now - _benchmark_ts) > BENCHMARK_CACHE_TTL:
# Try yfinance first
try:
bm = yf.download(BENCHMARK_SYMBOL, period="1y", progress=False, auto_adjust=True)
if bm.empty or len(bm) < 100:
raise ValueError("insufficient data from yfinance")
_benchmark_close = bm["Close"].dropna()
_benchmark_close.index = pd.to_datetime(_benchmark_close.index).tz_localize(None)
_benchmark_ts = now
except Exception:
# Fallback to akshare
try:
import akshare as ak
raw = ak.stock_zh_index_daily(symbol="sh000300")
if raw is not None and not raw.empty:
raw["date"] = pd.to_datetime(raw["date"])
raw = raw.sort_values("date")
_benchmark_close = raw.set_index("date")["close"]
_benchmark_ts = now
else:
logger.warning("Benchmark: akshare returned empty")
return np.array([], dtype=np.float64)
except Exception as e2:
logger.warning(f"Benchmark all sources failed: {e2}")
return np.array([], dtype=np.float64)
end_ts = pd.Timestamp(end_date).tz_localize(None) if hasattr(pd.Timestamp(end_date), "tz") else pd.Timestamp(end_date)
mask = _benchmark_close.index <= end_ts
bm_slice = _benchmark_close[mask]
if len(bm_slice) < 2:
return np.array([], dtype=np.float64)
ret = bm_slice.pct_change().dropna().values
# Flatten in case of 2D (e.g. MultiIndex columns from yfinance)
if ret.ndim == 2 and ret.shape[1] == 1:
ret = ret.flatten()
return ret[-max_periods:] if len(ret) > max_periods else ret
# ===================================================================
# Individual factor computation helpers
# ===================================================================
def _compute_momentum_12m(df_slice: pd.DataFrame) -> dict:
"""过去12个月收益减去最近1个月收益.
经典动量因子 (Jegadeesh & Titman 1993):
momentum = r_12m_ago_to_1m_ago (skip most recent month)
"""
try:
close = df_slice["close"].dropna().values
if len(close) < 21:
return {"status": "error", "value": None, "detail": "insufficient data (<21 rows)"}
n_12m = min(252, len(close))
n_1m = min(21, len(close))
val = close[-1] / close[-n_12m] - 1 - (close[-1] / close[-n_1m] - 1)
return {
"status": "ok",
"value": float(val),
"detail": f"n_12m={n_12m}, n_1m={n_1m}",
}
except Exception as e:
return {"status": "error", "value": None, "detail": str(e)}
def _compute_reversal_1m(df_slice: pd.DataFrame) -> dict:
"""过去1个月收益 (短期反转因子)."""
try:
close = df_slice["close"].dropna().values
if len(close) < 21:
return {"status": "error", "value": None, "detail": "insufficient data (<21 rows)"}
val = close[-1] / close[-21] - 1
return {"status": "ok", "value": float(val), "detail": ""}
except Exception as e:
return {"status": "error", "value": None, "detail": str(e)}
def _compute_volatility_idio(df_slice: pd.DataFrame, market_returns: np.ndarray | None = None) -> dict:
"""残差波动率: 对市场回归后的残差标准差.
Args:
df_slice: OHLCV 切片
market_returns: 可选,全市场等权收益率序列 (numpy array)
"""
try:
close = df_slice["close"].dropna()
if len(close) < 30:
return {"status": "error", "value": None, "detail": "insufficient data (<30 rows)"}
stock_ret = close.pct_change().dropna().values
end_date = pd.Timestamp(df_slice["date"].iloc[-1])
if market_returns is not None and len(market_returns) > 20:
bm_ret = market_returns
else:
bm_ret = _get_benchmark_returns(end_date, 504)
if len(bm_ret) < 20:
return {"status": "error", "value": None, "detail": f"insufficient benchmark data ({len(bm_ret)})"}
# Align lengths to the shorter series
min_len = min(len(stock_ret), len(bm_ret))
stock_ret = stock_ret[-min_len:]
bm_ret = bm_ret[-min_len:]
# Remove any NaN/inf values
mask = np.isfinite(stock_ret) & np.isfinite(bm_ret)
stock_ret = stock_ret[mask]
bm_ret = bm_ret[mask]
if len(stock_ret) < 20:
return {"status": "error", "value": None, "detail": f"too few valid returns ({len(stock_ret)})"}
X = np.column_stack([np.ones(len(stock_ret), dtype=np.float64), bm_ret])
y = stock_ret
beta = np.linalg.lstsq(X, y, rcond=None)[0]
residuals = y - X @ beta
ivol = float(np.std(residuals))
return {"status": "ok", "value": ivol, "detail": f"beta={beta[1]:.4f}, alpha={beta[0]:.6f}, n={len(stock_ret)}"}
except Exception as e:
return {"status": "error", "value": None, "detail": str(e)}
def _compute_beta_60d(df_slice: pd.DataFrame, market_returns: np.ndarray | None = None) -> dict:
"""60 日市场 beta。
优先使用全市场等权收益率作为基准 (从缓存读取),
如果不可用则回退到 CSI 300。
beta = Cov(R_i, R_m) / Var(R_m)
Args:
df_slice: OHLCV 切片
market_returns: 可选,全市场等权收益率序列 (numpy array)
"""
try:
close = df_slice["close"]
if len(close) < 61:
return {"status": "error", "value": None, "detail": "insufficient data (<61 rows)"}
stock_ret = close.pct_change().dropna().values[-60:]
# 优先使用全市场等权收益率
if market_returns is not None and len(market_returns) >= 20:
bm_ret = market_returns[-60:] if len(market_returns) >= 60 else market_returns
else:
end_date = pd.Timestamp(df_slice["date"].iloc[-1])
bm_ret = _get_benchmark_returns(end_date, 60)
if len(bm_ret) < 20:
return {"status": "error", "value": None, "detail": f"insufficient benchmark data ({len(bm_ret)})"}
min_len = min(len(stock_ret), len(bm_ret))
stock_ret = stock_ret[-min_len:]
bm_ret = bm_ret[-min_len:]
if min_len < 10:
return {"status": "error", "value": None, "detail": "insufficient data after alignment"}
cov = np.cov(stock_ret, bm_ret)
beta = cov[0, 1] / cov[1, 1] if cov[1, 1] > 1e-12 else 0.0
return {"status": "ok", "value": float(beta), "detail": f"n={min_len}"}
except Exception as e:
return {"status": "error", "value": None, "detail": str(e)}
def _compute_turnover_avg(df_slice: pd.DataFrame, shares_outstanding: int | None) -> dict:
"""20 日平均换手率 = 平均日成交量 / 流通股数."""
try:
volume = df_slice["volume"].values
if len(volume) < 20:
return {"status": "error", "value": None, "detail": "insufficient data (<20 rows)"}
avg_vol = float(np.mean(volume[-20:]))
if shares_outstanding is None or shares_outstanding <= 0:
return {"status": "error", "value": None, "detail": "shares_outstanding not available"}
turnover = avg_vol / shares_outstanding
return {
"status": "ok",
"value": float(turnover),
"detail": f"avg_vol={avg_vol:.0f}, shares={shares_outstanding}",
}
except Exception as e:
return {"status": "error", "value": None, "detail": str(e)}
# ===================================================================
# yfinance info helpers (with LRU cache)
# ===================================================================
@lru_cache(maxsize=4096)
def _get_info_field_cached(symbol: str, field: str) -> tuple[str, float | None, str]:
"""Cached wrapper for single info field fetch.
Checks local priors_cache/yfinance_info.parquet first, falls back to yfinance.info.
"""
# Try cache first
try:
cache_path = Path(__file__).parent / "priors_cache" / "yfinance_info.parquet"
if cache_path.exists():
# Use LRU cache on the parquet read itself
if not hasattr(_get_info_field_cached, "_cache_df"):
_get_info_field_cached._cache_df = pd.read_parquet(cache_path)
cache_df = _get_info_field_cached._cache_df
# Combined cache uses internal format (sh600000); symbol may be yfinance format (600000.SS)
lookup_keys = [symbol]
if symbol.endswith(".SS"):
lookup_keys.append("sh" + symbol[:-3])
elif symbol.endswith(".SZ"):
lookup_keys.append("sz" + symbol[:-3])
row = cache_df[cache_df["symbol"].isin(lookup_keys)]
if len(row) > 0 and field in row.columns:
val = row.iloc[0][field]
if val is not None and not (isinstance(val, float) and np.isnan(val)):
try:
return ("ok", float(val), "cached")
except (TypeError, ValueError):
pass
except Exception:
pass
# Fallback to yfinance
try:
ticker = yf.Ticker(symbol)
info = ticker.info
if info and field in info and info[field] is not None:
try:
val = float(info[field])
return ("ok", val, "")
except (TypeError, ValueError):
return ("error", None, f"field '{field}' value not numeric: {info[field]}")
else:
return ("error", None, f"field '{field}' not in info")
except Exception as e:
return ("error", None, str(e))
@lru_cache(maxsize=4096)
def _get_shares_outstanding_cached(symbol: str) -> int | None:
"""Get shares outstanding from yfinance info (cached)."""
try:
ticker = yf.Ticker(symbol)
info = ticker.info
if info:
for field in ["sharesOutstanding", "impliedSharesOutstanding", "floatShares"]:
val = info.get(field)
if val is not None and val > 0:
return int(val)
return None
except Exception:
return None
def _compute_size(yf_sym: str, cached_info: dict | None = None) -> dict:
"""log(Market Cap)."""
if cached_info is not None:
val = cached_info.get("marketCap")
if val is not None and val > 0:
return {"status": "ok", "value": float(np.log(val)), "detail": f"raw_marketCap={val:.0f} (cached)"}
status, val, detail = _get_info_field_cached(yf_sym, "marketCap")
if status == "ok" and val is not None and val > 0:
return {"status": "ok", "value": float(np.log(val)), "detail": f"raw_marketCap={val:.0f}"}
return {"status": status, "value": None, "detail": detail}
def _compute_pe(yf_sym: str, cached_info: dict | None = None) -> dict:
"""市盈率 (Price/Earnings)."""
if cached_info is not None:
val = cached_info.get("trailingPE")
if val is not None:
return {"status": "ok", "value": val, "detail": "cached"}
status, val, detail = _get_info_field_cached(yf_sym, "trailingPE")
return {"status": status, "value": val, "detail": detail}
def _compute_pb(yf_sym: str, cached_info: dict | None = None) -> dict:
"""市净率 (Price/Book)."""
if cached_info is not None:
val = cached_info.get("priceToBook")
if val is not None:
return {"status": "ok", "value": val, "detail": "cached"}
status, val, detail = _get_info_field_cached(yf_sym, "priceToBook")
return {"status": status, "value": val, "detail": detail}
def _compute_ps(yf_sym: str, cached_info: dict | None = None) -> dict:
"""市销率 (Price/Sales)."""
if cached_info is not None:
val = cached_info.get("priceToSalesTrailing12Months")
if val is not None:
return {"status": "ok", "value": val, "detail": "cached"}
status, val, detail = _get_info_field_cached(yf_sym, "priceToSalesTrailing12Months")
return {"status": status, "value": val, "detail": detail}
def _compute_dividend_yield(yf_sym: str, cached_info: dict | None = None) -> dict:
"""股息率."""
if cached_info is not None:
val = cached_info.get("dividendYield")
if val is not None:
return {"status": "ok", "value": val, "detail": "cached"}
val = cached_info.get("trailingAnnualDividendYield")
if val is not None:
return {"status": "ok", "value": val, "detail": "cached (trailing)"}
status, val, detail = _get_info_field_cached(yf_sym, "dividendYield")
if status == "ok":
return {"status": status, "value": val, "detail": detail}
status, val, detail = _get_info_field_cached(yf_sym, "trailingAnnualDividendYield")
return {"status": status, "value": val, "detail": detail}
def _get_shares_from_cache_or_api(yf_sym: str, cached_info: dict | None = None) -> int | None:
"""从缓存或 API 获取流通股数。"""
if cached_info is not None:
for field in ["sharesOutstanding", "impliedSharesOutstanding", "floatShares"]:
val = cached_info.get(field)
if val is not None and val > 0:
return int(val)
return _get_shares_outstanding_cached(yf_sym)
# ===================================================================
# akshare financial data(带超时保护)
# ===================================================================
@lru_cache(maxsize=8192)
def _compute_akshare_financial(symbol: str) -> dict:
"""从 akshare 获取最新年度财务摘要: ROE, 毛利率, 总资产增长率.
优先读缓存(priors_cache/{symbol}/financial.parquet)。
Returns:
dict with status, value (dict with keys roe/gross_margin/asset_growth or None), detail
"""
# Try cache first
cached = load_cached_financial(symbol)
if cached is not None:
return {
"status": "ok",
"value": {"roe": cached["roe"], "gross_margin": cached["gross_margin"],
"asset_growth": cached["asset_growth"]},
"detail": "from cache"
}
# No cache — skip akshare (can hang), return None gracefully
return {"status": "error", "value": None, "detail": "not in cache, akshare skipped"}
sym_num = re.sub(r"[^0-9]", "", symbol)
if not sym_num:
return {"status": "error", "value": None, "detail": f"cannot parse symbol: {symbol}"}
errors = []
result = {"roe": None, "gross_margin": None, "asset_growth": None}
# ── Part 1: ROE and Gross Margin from stock_financial_abstract ──
try:
df = ak.stock_financial_abstract(symbol=sym_num)
if df is not None and not df.empty and '指标' in df.columns:
date_cols = [c for c in df.columns if c not in ('选项', '指标') and re.match(r'^\d{8}$', str(c))]
if not date_cols:
date_cols = sorted([c for c in df.columns if c not in ('选项', '指标')], reverse=True)
else:
date_cols = sorted(date_cols, reverse=True)
if date_cols:
for _, row in df.iterrows():
indicator = str(row['指标'])
val = None
for dc in date_cols:
v = row.get(dc)
try:
vf = float(v) if v is not None else None
except (ValueError, TypeError):
vf = None
if vf is not None and np.isfinite(vf):
val = vf
break
if val is None:
continue
if '净资产收益率' in indicator and 'ROE' in indicator:
if result['roe'] is None:
result['roe'] = val
elif indicator == '毛利率':
if result['gross_margin'] is None:
result['gross_margin'] = val
if any(v is not None for v in result.values()):
errors.append("stock_financial_abstract: partial OK")
else:
errors.append("stock_financial_abstract: all fields missing")
else:
errors.append("stock_financial_abstract: empty or missing '指标' column")
except Exception as e:
errors.append(f"stock_financial_abstract: {e}")
# ── Part 2: Asset growth from stock_financial_debt_ths ──
try:
df_debt = ak.stock_financial_debt_ths(symbol=sym_num, indicator='按年度')
if df_debt is not None and not df_debt.empty:
ta_col = None
for candidate in ['*资产合计', '资产合计', '资产总计']:
if candidate in df_debt.columns:
ta_col = candidate
break
if ta_col is None:
for c in df_debt.columns:
if '资产合计' in str(c) or '资产总计' in str(c):
ta_col = c
break
if ta_col:
period_col = '报告期'
if period_col in df_debt.columns:
def _parse_chinese_num(s):
if s is None:
return None
s = str(s).strip()
if not s:
return None
try:
return float(s)
except ValueError:
pass
if '万亿' in s:
try:
return float(s.replace('万亿', '').replace(',', '').strip()) * 1e12
except ValueError:
pass
if '亿' in s:
try:
return float(s.replace('亿', '').replace(',', '').strip()) * 1e8
except ValueError:
pass
if '万' in s:
try:
return float(s.replace('万', '').replace(',', '').strip()) * 1e4
except ValueError:
pass
return None
years = []
for _, row in df_debt.iterrows():
try:
y = int(str(row[period_col])[:4])
years.append(y)
except (ValueError, TypeError):
years.append(None)
df_debt = df_debt.copy()
df_debt['_year'] = years
df_debt = df_debt.dropna(subset=['_year'])
df_debt = df_debt.sort_values('_year', ascending=False)
if len(df_debt) >= 2:
latest_ta = _parse_chinese_num(df_debt[ta_col].iloc[0])
prev_ta = _parse_chinese_num(df_debt[ta_col].iloc[1])
if latest_ta is not None and prev_ta is not None and prev_ta > 0:
growth = (latest_ta / prev_ta - 1) * 100
result['asset_growth'] = float(growth)
errors.append("asset_growth computed from stock_financial_debt_ths")
else:
errors.append("stock_financial_debt_ths: no total assets column found")
else:
errors.append("stock_financial_debt_ths: empty result")
except Exception as e:
errors.append(f"stock_financial_debt_ths: {e}")
if any(v is not None for v in result.values()):
return {"status": "ok", "value": result, "detail": "; ".join(errors)}
return {"status": "error", "value": None, "detail": "; ".join(errors) if errors else "all akshare APIs failed"}
def _timeout_akshare(symbol: str, timeout: int = 30) -> dict:
"""带超时保护的 akshare 财务数据下载。"""
result_container = [{"status": "error", "value": None, "detail": "timeout"}]
def runner():
try:
result_container[0] = _compute_akshare_financial(symbol)
except Exception as e:
result_container[0] = {"status": "error", "value": None, "detail": str(e)}
t = threading.Thread(target=runner, daemon=True)
t.start()
t.join(timeout)
return result_container[0]
# ===================================================================
# Main entry point
# ===================================================================
PRIOR_FACTOR_NAMES = [
"momentum_12m",
"reversal_1m",
"volatility_idio",
"beta_60d",
"turnover_avg",
"size",
"pe",
"pb",
"ps",
"dividend_yield",
"roe",
"gross_margin",
"asset_growth",
]
PRIOR_COLUMNS = [f"prior_{n}" for n in PRIOR_FACTOR_NAMES]
def compute_all_priors(
df_ohlcv: pd.DataFrame,
symbol: str,
date: pd.Timestamp,
use_cache: bool = False,
) -> dict[str, float | None]:
"""计算单只股票在某个日期的全部 13 个先验因子值.
使用 df_ohlcv 中截止到 date 的数据(防数据泄露).
Args:
df_ohlcv: OHLCV DataFrame with columns [date, open, high, low, close, volume].
symbol: 股票代码 (e.g., "sh600000").
date: 计算截止日期。
use_cache: 是否优先从 priors_cache 读取信息/财务数据。
Returns:
dict with prior_* keys and float values (None if computation failed).
"""
# Ensure date column is datetime (tz-naive) and slice up to date
if "date" in df_ohlcv.columns:
df = df_ohlcv.copy()
df["date"] = pd.to_datetime(df["date"]).dt.tz_localize(None)
target = pd.Timestamp(date).tz_localize(None) if hasattr(pd.Timestamp(date), "tz") else pd.Timestamp(date)
df_slice = df[df["date"] <= target].sort_values("date").reset_index(drop=True)
else:
df_slice = df_ohlcv.copy()
if len(df_slice) < 2:
return {f"prior_{k}": None for k in PRIOR_FACTOR_NAMES}
# Convert symbol to yfinance format
yf_sym = _to_yf(symbol)
# ── 从缓存读取可选数据 ──
cached_info: dict | None = None
cached_financial: dict | None = None
market_returns_series: pd.Series | None = None
if use_cache:
cached_info = load_cached_info(symbol)
cached_financial = load_cached_financial(symbol)
market_returns_series = load_cached_market_returns()
# 将 market_returns 转换为 numpy array(对齐到日期)
market_returns_arr: np.ndarray | None = None
if market_returns_series is not None and not market_returns_series.empty:
target_date = pd.Timestamp(date).tz_localize(None) if hasattr(pd.Timestamp(date), "tz") else pd.Timestamp(date)
mr = market_returns_series[market_returns_series.index <= target_date]
if len(mr) > 10:
market_returns_arr = mr.values[-252:] # 最多 1 年数据
# ── Price-based factors ──
momentum = _compute_momentum_12m(df_slice)
reversal = _compute_reversal_1m(df_slice)
vol_idio = _compute_volatility_idio(df_slice, market_returns_arr)
beta = _compute_beta_60d(df_slice, market_returns_arr)
# Turnover needs shares outstanding
if use_cache and cached_info is not None:
shares_out = _get_shares_from_cache_or_api(yf_sym, cached_info)
else:
shares_out = _get_shares_outstanding_cached(yf_sym)
turnover = _compute_turnover_avg(df_slice, shares_out)
# ── yfinance info-based factors ──
size_val = _compute_size(yf_sym, cached_info)
pe_val = _compute_pe(yf_sym, cached_info)
pb_val = _compute_pb(yf_sym, cached_info)
ps_val = _compute_ps(yf_sym, cached_info)
dy_val = _compute_dividend_yield(yf_sym, cached_info)
# ── akshare financial factors — 被 A1 验证排除(静态值无时间信号,拖累 IC)
# 详见: https://github.com/cedricwyh/Project-Jinjing/issues/... (TODO)
roe_val = {"status": "error", "value": None, "detail": "excluded in A1 — static values hurt IC"}
gm_val = {"status": "error", "value": None, "detail": "excluded in A1"}
ag_val = {"status": "error", "value": None, "detail": "excluded in A1"}
# ── Compile results ──
results = {}
for name, result in [
("prior_momentum_12m", momentum),
("prior_reversal_1m", reversal),
("prior_volatility_idio", vol_idio),
("prior_beta_60d", beta),
("prior_turnover_avg", turnover),
("prior_size", size_val),
("prior_pe", pe_val),
("prior_pb", pb_val),
("prior_ps", ps_val),
("prior_dividend_yield", dy_val),
("prior_roe", roe_val),
("prior_gross_margin", gm_val),
("prior_asset_growth", ag_val),
]:
if isinstance(result, dict):
results[name] = result.get("value")
else:
results[name] = result
return results
def compute_all_priors_batch(
symbols: list[str],
ohlcv_dict: dict[str, pd.DataFrame],
date: pd.Timestamp,
verbose: bool = True,
use_cache: bool = False,
) -> pd.DataFrame:
"""批量计算多个股票的先验因子.
Args:
symbols: 股票代码列表
ohlcv_dict: {symbol: OHLCV DataFrame} 字典
date: 计算截止日期
verbose: 是否显示进度
use_cache: 是否优先从缓存读取
Returns:
DataFrame with columns [symbol] + prior_* columns
"""
rows = []
iterator = enumerate(symbols)
if verbose:
try:
from tqdm import tqdm
iterator = tqdm(list(enumerate(symbols)), desc="Priors")
except ImportError:
pass
for idx, sym in iterator:
ohlcv = ohlcv_dict.get(sym)
if ohlcv is None or len(ohlcv) < 2:
row = {"symbol": sym}
for pcol in PRIOR_COLUMNS:
row[pcol] = None
rows.append(row)
continue
priors = compute_all_priors(ohlcv, sym, date, use_cache=use_cache)
row = {"symbol": sym}
row.update(priors)
rows.append(row)
if not verbose and (idx + 1) % 100 == 0:
logger.info(f" Priors: {idx + 1}/{len(symbols)}")
return pd.DataFrame(rows)