"""同口径全年目标减累计实际;剩余期间保持整体,不暗填季节分配。""" import json from decimal import Decimal as D, InvalidOperation from statistics import median def finite(value): try: number = D(str(value)) except (InvalidOperation, ValueError, TypeError) as exc: raise ValueError("invalid_numeric_input") from exc if not number.is_finite(): raise ValueError("nonfinite_profit_input") return number contract = {"symbol": "AAA", "year": 2026, "currency": "CNY", "scope": "parent_net_profit", "unit": "million"} def remaining(target, actual, historical=(), constraint=None): for field in contract: if target[field] != actual[field]: raise ValueError("incompatible_"+field) if target["through_quarter"] != 4 or actual["through_quarter"] not in [1, 2, 3]: raise ValueError("invalid_period") required = finite(target["profit"])-finite(actual["profit"]) quarters = list(range(actual["through_quarter"]+1, 5)) history = [finite(x) for x in historical] benchmark = median(history) if history else None uplift = required/benchmark-1 if benchmark is not None and benchmark > 0 else None cap = finite(constraint) if constraint is not None else None return {"remaining_quarters": quarters, "required_total": str(required), "historical_median": str(benchmark) if benchmark is not None else None, "uplift": str(uplift) if uplift is not None else None, "exceeds_supplied_constraint": required > cap if cap is not None else None, "already_met": required <= 0, "quarter_allocation": None} def profit_from_eps(eps, shares_million): if shares_million is None: return {"profit": None, "reason": "missing_share_assumption"} shares = finite(shares_million) if shares <= 0: raise ValueError("invalid_shares") return {"profit": str(finite(eps)*shares), "reason": None} target = {**contract, "through_quarter": 4, "profit": "400"} actual = {**contract, "through_quarter": 3, "profit": "250"} main = remaining(target, actual, ["100", "120", "140"], "145") assert main["required_total"] == "150" and main["uplift"] == "0.25" assert main["exceeds_supplied_constraint"] is True half = remaining(target, {**actual, "through_quarter": 2, "profit": "180"}) assert half["required_total"] == "220" and half["remaining_quarters"] == [3, 4] and half["quarter_allocation"] is None met = remaining(target, {**actual, "profit": "450"}) assert met["required_total"] == "-50" and met["already_met"] assert profit_from_eps("4", "100")["profit"] == "400" assert profit_from_eps("4", None)["profit"] is None for token in ["NaN", "Infinity", "-Infinity"]: for kwargs in [{"historical": [token]}, {"constraint": token}]: try: remaining(target, actual, **kwargs) except ValueError: pass else: raise AssertionError("非有限比较值必须阻断") try: remaining(target, {**actual, "profit": token}) except ValueError: pass else: raise AssertionError("非有限实际必须阻断") print(json.dumps({"nine_months": main, "half_year": half, "target_already_met": met, "eps_without_shares": profit_from_eps("4", None)}, sort_keys=True))