Spaces:
Sleeping

File size: 4,327 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
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