tradingSystem/research/micro_calibration_20261028/engine.py

184 lines
9.0 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""原冻结研究引擎的独立副本。保留逐笔成交约束,不导入生产服务。
来源:macro_timing_20261026/micro100.py与timed_micro100.py;来源摘要见protocol_sources.json。
本文件只提取positive、Basket、TimingStrategy,并把m.Basket改为同文件Basket。
"""
import math
def positive(x):
return isinstance(x, (float, int)) and math.isfinite(x) and x > 0
class Basket:
"""可分割复权单位;先卖后买,只交易成员变化。cost为成交额单边摩擦。"""
def __init__(self, cost=.003, constrain=True):
self.cost = cost
self.constrain = constrain
self.cash = 1.
self.units = {}
self.last = {}
self.stale = {}
self.records = []
self.trades = []
self.failures = []
@staticmethod
def quote(r, field):
if r and positive(r.get(field)) and positive(r.get("adj_factor")):
return r[field] * r["adj_factor"]
return None
def allowed(self, r, lim, side):
if not self.quote(r, "open") or not positive(r.get("vol")):
return "停牌或缺开盘报价"
if self.constrain:
key = "up_limit" if side == "buy" else "down_limit"
if not lim or not positive(lim.get(key)):
return "缺历史涨跌停价"
if side == "buy" and r["open"] >= lim[key] - .00001:
return "开盘涨停"
if side == "sell" and r["open"] <= lim[key] + .00001:
return "开盘跌停"
return None
def value(self, code, rows, field):
q = self.quote(rows.get(code), field)
if q is None:
q = self.last.get(code, 0.) if self.stale.get(code, 0) <= 20 else 0.
return self.units[code] * q
def step(self, day, target, rows, limits, current_risk=frozenset()):
target = set(target)
for code in self.units:
self.stale[code] = 0 if self.quote(rows.get(code), "close") else self.stale.get(code, 0) + 1
opening = self.cash + sum(self.value(c, rows, "open") for c in self.units)
traded, fee = 0., 0.
for code in sorted(set(self.units) - target):
fail = self.allowed(rows.get(code), limits.get(code), "sell")
if fail:
self.failures.append({"date": day, "code": code, "side": "sell", "reason": fail})
continue
units = self.units.pop(code)
value = units * self.quote(rows[code], "open")
self.cash += value * (1-self.cost)
traded += value
fee += value*self.cost
self.trades.append({"date": day, "code": code, "side": "sell", "value": value, "fee": value*self.cost,
"adjusted_units": units, "adjusted_open": self.quote(rows[code],"open")})
missing = sorted(target - self.units.keys())
budget = self.cash / len(missing) if missing else 0.
for code in missing:
fail = "开盘已风险警示" if code in current_risk else self.allowed(rows.get(code), limits.get(code), "buy")
if fail:
self.failures.append({"date": day, "code": code, "side": "buy", "reason": fail})
continue
if budget <= 1e-15:
continue
value = budget / (1+self.cost)
self.units[code] = value / self.quote(rows[code], "open")
self.cash -= budget
self.stale[code] = 0
traded += value
fee += value*self.cost
self.trades.append({"date": day, "code": code, "side": "buy", "value": value, "fee": value*self.cost,
"adjusted_units": self.units[code], "adjusted_open": self.quote(rows[code],"open")})
closing = self.cash + sum(self.value(c, rows, "close") for c in self.units)
for code in self.units:
q = self.quote(rows.get(code), "close")
if q is not None:
self.last[code] = q
row = {"date": day, "open_nav_before_trade": opening, "nav": closing, "cash": self.cash,
"turnover_two_sided": traded/opening if opening else None, "fee": fee,
"positions": len(self.units), "target_count": len(target),
"stale_positions": sum(self.stale.get(c, 0)>0 for c in self.units),
"zero_mark_positions": sum(self.stale.get(c, 0)>20 for c in self.units)}
self.records.append(row)
if self.cash < -1e-10:
raise ValueError("研究组合出现负现金")
return row
class TimingStrategy:
def __init__(self, mode="combined", cost=.003, high_key="high"):
self.mode=mode
self.high_key=high_key
self.basket=Basket(cost=cost)
self.state="flat"
self.pending=None
self.active=None
self.cycles=[]
self.decisions=[]
self.next_id=1
def entry_reason(self, signal):
if self.mode=="always":return "unconditional"
growth=signal["growth_break"] and self.mode in ("combined","growth")
low=signal["low"] and self.mode in ("combined","low")
if growth and low:return "growth_and_low"
if growth:return "growth_break"
if low:return "low_liquidity"
return None
def step(self, day, members, rows, limits, risk, signal):
action=self.pending
old_state=self.state
target=action["members"] if action and action["action"] in ("enter","hold") else []
begin_trades=len(self.basket.trades)
if action and action["action"]=="enter":
assert self.active is None and not self.basket.units
self.active={"id":self.next_id,"signal_date":action["date"],"entry_date":day,
"reason":action["reason"],"entry_nav":self.basket.cash,
"entry_position":len(self.basket.records),"first_buy_date":None,
"exit_signal_date":None,"exit_date":None,"status":"holding",
"signal_percentile":action["percentile"],"path":[self.basket.cash]}
self.next_id+=1
self.state="holding"
record=self.basket.step(day,target,rows,limits,risk)
if self.active:
self.active["path"].append(record["nav"])
new_trades=self.basket.trades[begin_trades:]
if not self.active["first_buy_date"] and any(t["side"]=="buy" for t in new_trades):
self.active["first_buy_date"]=day
cycle_id=self.active["id"] if self.active else None
if self.state=="exiting" and not self.basket.units:
assert self.active is not None
self.active.update(exit_date=day,exit_nav=self.basket.cash,
return_value=self.basket.cash/self.active["entry_nav"]-1,
status="closed" if self.active["first_buy_date"] else "never_filled",
holding_trade_days=len(self.basket.records)-1-self.active["entry_position"])
self.cycles.append(self.active)
self.active=None
self.state="flat"
high=bool(signal[self.high_key]) and self.mode!="always"
reason=self.entry_reason(signal)
if self.state=="exiting":
self.pending={"action":"exit","date":day,"members":[],"reason":"continue_exit"}
elif self.state=="holding" and high:
self.state="exiting"
self.active["exit_signal_date"]=day
self.active["exit_signal_percentile"]=signal["activity_percentile"]
self.pending={"action":"exit","date":day,"members":[],"reason":"high_liquidity"}
elif self.state=="holding":
self.pending={"action":"hold","date":day,"members":list(members),"reason":"daily_membership"}
elif reason and not high:
self.pending={"action":"enter","date":day,"members":list(members),"reason":reason,
"percentile":signal["activity_percentile"]}
else:
self.pending=None
decision={"date":day,"state_at_open":old_state,"state_after_close":self.state,
"executed_action":action["action"] if action else "cash",
"executed_signal_date":action["date"] if action else None,
"next_action":self.pending["action"] if self.pending else "cash",
"next_reason":self.pending["reason"] if self.pending else None,
"low":signal["low"],"growth_break":signal["growth_break"],"high":high,
"entry_vetoed_by_high":self.state=="flat" and bool(reason) and high,
"cycle_id":cycle_id}
self.decisions.append(decision)
return record,decision
def cycles_at_end(self):
result=[dict(c) for c in self.cycles]
if self.active:
result.append({**self.active,"status":"open_at_cutoff","valuation_date":self.basket.records[-1]["date"],
"exit_nav":None,"return_value":self.basket.records[-1]["nav"]/self.active["entry_nav"]-1,
"holding_trade_days":len(self.basket.records)-self.active["entry_position"]})
return result