Spaces:
Sleeping
Sleeping
Download factor_engine.py from zbgool/quant-engine: direct link, hf CLI and curl.
- Browser
- Download file 4.33 kB
-
https://huggingface.co/spaces/zbgool/quant-engine/resolve/main/factor_engine.py
- Command line
-
hf download hf://spaces/zbgool/quant-engine/factor_engine.py
-
curl -L -o factor_engine.py https://huggingface.co/spaces/zbgool/quant-engine/resolve/main/factor_engine.py
4.33 kB
| import logging | |
| import pandas as pd | |
| import numpy as np | |
| logger = logging.getLogger(__name__) | |
| # 抑制 pandas 2.x 的 FutureWarning: fillna/ffill/bfill 对 object dtype 自动降级即将移除 | |
| pd.set_option("future.no_silent_downcasting", True) | |
| def evaluate_formula( | |
| formula: str, | |
| stock_data: pd.DataFrame, | |
| extra_variables: dict[str, pd.Series] | None = None, | |
| ) -> pd.Series: | |
| """ | |
| 安全执行因子公式,返回因子值序列 | |
| 支持的变量: close, open, high, low, volume, amount | |
| extra_variables: 多周期变量(如 w_close, m5_volume),合并到公式沙盒 | |
| 支持 pandas/numpy 操作 | |
| """ | |
| safe_globals = { | |
| "__builtins__": {}, | |
| "pd": pd, | |
| "np": np, | |
| "abs": abs, | |
| "min": min, | |
| "max": max, | |
| "sum": sum, | |
| "round": round, | |
| "len": len, | |
| "pow": pow, | |
| "int": int, | |
| "float": float, | |
| "bool": bool, | |
| "str": str, | |
| "True": True, | |
| "False": False, | |
| "None": None, | |
| } | |
| local_vars = { | |
| "close": stock_data["close"], | |
| "open": stock_data["open"], | |
| "high": stock_data["high"], | |
| "low": stock_data["low"], | |
| "volume": stock_data["volume"], | |
| "amount": stock_data["amount"], | |
| } | |
| # 合并多周期变量 | |
| if extra_variables: | |
| local_vars.update(extra_variables) | |
| try: | |
| # 先尝试 eval(单行表达式) | |
| result = eval(formula, safe_globals, local_vars) | |
| except SyntaxError: | |
| # 多行公式或含赋值语句,用 exec | |
| try: | |
| exec(compile(formula, "<formula>", "exec"), safe_globals, local_vars) | |
| # 按优先级查找结果变量: result > factor > 最后一个赋值变量 | |
| input_keys = {"close", "open", "high", "low", "volume", "amount", | |
| "pd", "np", "abs", "min", "max", "sum", "round", | |
| "len", "pow", "int", "float", "bool", "str", | |
| "True", "False", "None"} | |
| if extra_variables: | |
| input_keys.update(extra_variables.keys()) | |
| result = local_vars.get("result") or local_vars.get("factor") | |
| if result is None: | |
| # 取最后一个被赋值的新变量 | |
| for key in reversed(list(local_vars.keys())): | |
| if key not in input_keys and not key.startswith("_"): | |
| val = local_vars[key] | |
| if isinstance(val, (pd.Series, pd.DataFrame)): | |
| result = val | |
| break | |
| if result is None: | |
| raise ValueError("公式需要将最终结果赋值给变量(建议命名为 factor 或 result)") | |
| except ValueError: | |
| raise | |
| except Exception as e: | |
| raise ValueError(f"公式执行错误: {e}") | |
| except Exception as e: | |
| raise ValueError(f"公式执行错误: {e}") | |
| if isinstance(result, pd.Series): | |
| return result | |
| elif isinstance(result, (int, float, np.floating)): | |
| return pd.Series(result, index=stock_data.index) | |
| else: | |
| return pd.Series(result, index=stock_data.index) | |
| def evaluate_formula_batch( | |
| formula: str, | |
| stocks_data: dict[str, pd.DataFrame], | |
| multi_tf_variables: dict[str, dict[str, pd.Series]] | None = None, | |
| ) -> dict[str, pd.Series]: | |
| """ | |
| 批量计算所有股票的因子值(单进程,避免 Windows 多进程序列化问题) | |
| multi_tf_variables: {股票代码: {变量名: Series}} 多周期变量 | |
| 返回 {股票代码: 因子值序列} | |
| """ | |
| if not stocks_data: | |
| return {} | |
| result = {} | |
| errors = 0 | |
| first_error = "" | |
| for code, df in stocks_data.items(): | |
| try: | |
| extra = multi_tf_variables.get(code) if multi_tf_variables else None | |
| result[code] = evaluate_formula(formula, df, extra_variables=extra) | |
| except Exception as e: | |
| errors += 1 | |
| if errors <= 3: | |
| logger.warning(f"{code} 计算失败: {e}") | |
| if errors == 1: | |
| first_error = str(e) | |
| if errors: | |
| logger.info(f"共 {errors}/{len(stocks_data)} 只失败") | |
| if not result and first_error: | |
| raise ValueError(first_error) | |
| return result | |