243 lines
12 KiB
Python
243 lines
12 KiB
Python
|
|
"""微盘轮换状态与订单计算。纯函数,无行情、数据库或下单依赖。"""
|
|||
|
|
import copy
|
|||
|
|
import datetime as dt
|
|||
|
|
import hashlib
|
|||
|
|
import json
|
|||
|
|
import math
|
|||
|
|
|
|||
|
|
RULE = 'micro30-v1-20261027'
|
|||
|
|
SIZE = 30
|
|||
|
|
PHASES = ('original', 'entering_micro', 'micro', 'returning_original')
|
|||
|
|
|
|||
|
|
|
|||
|
|
def initial_state():
|
|||
|
|
return {'phase': 'original', 'cycle': 0, 'last_snapshot': None, 'entry_date': None,
|
|||
|
|
'exit_date': None, 'reason': None, 'target': [], 'entry_budget': 0., 'disabled': False,
|
|||
|
|
'entry_quantities': {}, 'consumed_entry': None, 'closed_date': None}
|
|||
|
|
|
|||
|
|
|
|||
|
|
def snapshot_check(value, execution_date, *, require_frozen=True):
|
|||
|
|
errors = []
|
|||
|
|
if not isinstance(value, dict):
|
|||
|
|
return ['没有监控快照']
|
|||
|
|
if value.get('rule_version') != RULE or value.get('basket_size') != SIZE:
|
|||
|
|
errors.append('策略规则版本不一致')
|
|||
|
|
if value.get('effective_date') != execution_date or str(value.get('data_date', '')) >= execution_date:
|
|||
|
|
errors.append('快照日期不适用于本次执行')
|
|||
|
|
if require_frozen and value.get('frozen') is not True:
|
|||
|
|
errors.append('执行快照尚未冻结')
|
|||
|
|
keys = ('rule_version', 'basket_size', 'data_date', 'effective_date', 'signal_ready',
|
|||
|
|
'basket_ready', 'signal', 'members', 'source_hashes', 'errors')
|
|||
|
|
try:
|
|||
|
|
body = {k: value[k] for k in keys}
|
|||
|
|
digest = hashlib.sha256(json.dumps(body, sort_keys=True, ensure_ascii=False,
|
|||
|
|
separators=(',', ':'), allow_nan=False).encode()).hexdigest()
|
|||
|
|
if digest != value.get('snapshot_version'):
|
|||
|
|
errors.append('快照摘要不一致')
|
|||
|
|
signal = value['signal']
|
|||
|
|
if signal.get('date') != value['data_date'] or signal.get('ready') is not value['signal_ready']:
|
|||
|
|
errors.append('信号就绪或日期字段冲突')
|
|||
|
|
if any(type(signal.get(k)) is not bool for k in ('growth_break', 'low', 'high')):
|
|||
|
|
errors.append('信号必须是明确的布尔值')
|
|||
|
|
if value['basket_ready']:
|
|||
|
|
members = value['members']
|
|||
|
|
if len(members) != SIZE or len({m['code'] for m in members}) != SIZE:
|
|||
|
|
errors.append('目标名单不是30只唯一股票')
|
|||
|
|
if any(m.get('eligible') is not True or m.get('rank') != i+1 for i, m in enumerate(members)):
|
|||
|
|
errors.append('名单资格或排名不完整')
|
|||
|
|
except (KeyError, ValueError, TypeError):
|
|||
|
|
errors.append('快照字段不完整或数字非法')
|
|||
|
|
return errors
|
|||
|
|
|
|||
|
|
|
|||
|
|
def transition(state, snapshot, *, micro_qty, original_qty, budget, control='run'):
|
|||
|
|
s = copy.deepcopy(state)
|
|||
|
|
if s['phase'] not in PHASES:
|
|||
|
|
raise ValueError('未知轮换阶段')
|
|||
|
|
ready = bool(snapshot and snapshot.get('signal_ready'))
|
|||
|
|
signal = snapshot['signal'] if ready else {}
|
|||
|
|
if control == 'pause_all':
|
|||
|
|
return s
|
|||
|
|
if control == 'exit_disable':
|
|||
|
|
s['disabled'] = True
|
|||
|
|
if s['phase'] != 'original' or micro_qty:
|
|||
|
|
s['phase'], s['reason'] = 'returning_original', '用户退出并停用'
|
|||
|
|
if ready and signal.get('high') and s['phase'] in ('entering_micro', 'micro'):
|
|||
|
|
s.update(phase='returning_original', exit_date=snapshot['effective_date'], reason='微盘活跃度高位')
|
|||
|
|
if s['phase'] == 'returning_original' and micro_qty == 0:
|
|||
|
|
s.update(phase='original', target=[], entry_budget=0., entry_quantities={},
|
|||
|
|
closed_date=(snapshot or {}).get('effective_date') or s.get('exit_date'))
|
|||
|
|
return s # 清完当天不立即重开下一轮。
|
|||
|
|
fresh_entry = snapshot and snapshot.get('snapshot_version') != s.get('consumed_entry') and snapshot.get('effective_date') != s.get('closed_date')
|
|||
|
|
if s['phase'] == 'original' and fresh_entry and not s['disabled'] and control == 'run' and ready and snapshot.get('basket_ready') and not signal.get('high') and (signal.get('growth_break') or signal.get('low')):
|
|||
|
|
if micro_qty:
|
|||
|
|
raise ValueError('旧微盘持仓未清完,不能再次入场')
|
|||
|
|
s.update(phase='entering_micro', cycle=s['cycle']+1, entry_date=snapshot['effective_date'],
|
|||
|
|
entry_budget=max(0., budget), entry_quantities={}, consumed_entry=snapshot['snapshot_version'],
|
|||
|
|
reason='成长主线瓦解' if signal['growth_break'] else '微盘活跃度极低')
|
|||
|
|
if snapshot and snapshot.get('basket_ready') and s['phase'] in ('entering_micro', 'micro'):
|
|||
|
|
s['target'] = [r['code'] for r in snapshot['members']]
|
|||
|
|
if snapshot:
|
|||
|
|
s['last_snapshot'] = snapshot['snapshot_version']
|
|||
|
|
return s
|
|||
|
|
|
|||
|
|
|
|||
|
|
def board(code):
|
|||
|
|
if code.startswith('68'):
|
|||
|
|
return 'STAR'
|
|||
|
|
if code.startswith('30'):
|
|||
|
|
return 'CHINEXT'
|
|||
|
|
return 'MAIN'
|
|||
|
|
|
|||
|
|
|
|||
|
|
def min_qty(code):
|
|||
|
|
return 200 if board(code) == 'STAR' else 100
|
|||
|
|
|
|||
|
|
|
|||
|
|
def fee(value, side, *, rate=.0003, minimum=5., sell_tax=.0005, transfer_rate=.00001):
|
|||
|
|
return round(max(minimum, value*rate)+value*transfer_rate+(value*sell_tax if side == 'sell' else 0), 2)
|
|||
|
|
|
|||
|
|
|
|||
|
|
def buy_qty(code, price, budget, costs):
|
|||
|
|
if not math.isfinite(price) or price <= 0 or not math.isfinite(budget) or budget <= 0:
|
|||
|
|
return 0
|
|||
|
|
qty = int(budget/price)//100*100
|
|||
|
|
while qty >= min_qty(code) and qty*price+fee(qty*price, 'buy', **costs) > budget:
|
|||
|
|
qty -= 100
|
|||
|
|
return qty if qty >= min_qty(code) else 0
|
|||
|
|
|
|||
|
|
|
|||
|
|
def preflight(members, budget, allowed_boards, costs):
|
|||
|
|
issues = []
|
|||
|
|
if len(members) != SIZE:
|
|||
|
|
return ['目标名单数量不是30只']
|
|||
|
|
for m in members:
|
|||
|
|
if board(m['code']) not in allowed_boards:
|
|||
|
|
issues.append(m['code']+'板块权限未确认')
|
|||
|
|
if not buy_qty(m['code'], float(m['close']), budget/SIZE, costs):
|
|||
|
|
issues.append(m['code']+'等资金份额不足最小交易单位及费用')
|
|||
|
|
return issues
|
|||
|
|
|
|||
|
|
|
|||
|
|
def orders(state, snapshot, *, original, micro, quotes, cash, account_mv, cap_amount,
|
|||
|
|
reserve_cash=0., pending=(), control='run', blacklisted=(), costs=None):
|
|||
|
|
"""只形成意图,不把计划卖出计入现金。调用者落表后再执行。"""
|
|||
|
|
from app.core.planner import plan_reduce_exposure
|
|||
|
|
costs = costs or {}
|
|||
|
|
result, waits = [], []
|
|||
|
|
if control == 'pause_all':
|
|||
|
|
return result, ['用户暂停全部执行']
|
|||
|
|
active_codes = {r['ts_code'] for r in pending}
|
|||
|
|
original_by = {r['ts_code']: r for r in original if r.get('total_qty', 0) > 0}
|
|||
|
|
micro_by = {r['ts_code']: r for r in micro if r.get('total_qty', 0) > 0}
|
|||
|
|
phase = state['phase']
|
|||
|
|
if phase == 'entering_micro':
|
|||
|
|
positions = [{**p, 'price': quotes.get(c, {}).get('price')} for c, p in original_by.items()]
|
|||
|
|
release = sum(p['total_qty']*p['price'] for p in positions if p.get('price'))
|
|||
|
|
plan = plan_reduce_exposure(release_amount=release, positions=positions)
|
|||
|
|
seen = set()
|
|||
|
|
for item in plan['items']:
|
|||
|
|
if item['side'] != 'sell':
|
|||
|
|
continue
|
|||
|
|
c = item['ts_code']
|
|||
|
|
if c in seen:
|
|||
|
|
continue
|
|||
|
|
seen.add(c)
|
|||
|
|
# 同股先完成加仓部分,再由下一跳重算剩余批次;不能提前整股清仓。
|
|||
|
|
result.append({'book_id': 'original', 'ts_code': c, 'side': 'sell',
|
|||
|
|
'qty': min(int(item['qty']), original_by[c]['total_qty']), 'reason': item['reason']})
|
|||
|
|
for c, p in original_by.items():
|
|||
|
|
if c not in seen and p.get('total_qty'):
|
|||
|
|
result.append({'book_id': 'original', 'ts_code': c, 'side': 'sell', 'qty': p['total_qty'], 'reason': '轮换剩余持仓退出'})
|
|||
|
|
target = set(state['target']) if phase in ('entering_micro', 'micro') else set()
|
|||
|
|
for c, p in micro_by.items():
|
|||
|
|
if phase == 'returning_original' or (snapshot and snapshot.get('basket_ready') and c not in target):
|
|||
|
|
result.append({'book_id': 'micro30', 'ts_code': c, 'side': 'sell', 'qty': p['total_qty'], 'reason': '高位清仓或成员调出'})
|
|||
|
|
result = [r for r in result if r['ts_code'] not in active_codes]
|
|||
|
|
if phase not in ('entering_micro', 'micro') or control != 'run' or not snapshot or not snapshot.get('basket_ready'):
|
|||
|
|
return result, waits
|
|||
|
|
available = max(0., min(cash-reserve_cash, cap_amount-account_mv))
|
|||
|
|
# 入场期间保留既定每股资金目标,以便原策略分批回款后继续完成建仓。
|
|||
|
|
missing = sorted(c for c in target if c not in micro_by)
|
|||
|
|
candidates = sorted(target) if phase == 'entering_micro' else missing
|
|||
|
|
per_new = available/len(missing) if missing else 0.
|
|||
|
|
for c in candidates:
|
|||
|
|
if c in original_by or c in active_codes or c in blacklisted:
|
|||
|
|
waits.append(c+'旧仓、在途委托或黑名单阻止买入')
|
|||
|
|
continue
|
|||
|
|
q = quotes.get(c, {})
|
|||
|
|
price = q.get('price')
|
|||
|
|
if not price or price <= 0:
|
|||
|
|
waits.append(c+'没有有效行情')
|
|||
|
|
continue
|
|||
|
|
owned_qty = micro_by.get(c, {}).get('total_qty', 0)
|
|||
|
|
if phase == 'entering_micro':
|
|||
|
|
quantities = state.setdefault('entry_quantities', {})
|
|||
|
|
# 首次有行情时固定数量,部分成交只补剩余,不随价格下跌重新等权。
|
|||
|
|
if c not in quantities:
|
|||
|
|
quantities[c] = buy_qty(c, price, state['entry_budget']/SIZE, costs)
|
|||
|
|
remaining_qty = max(0, quantities[c]-owned_qty)
|
|||
|
|
desired = remaining_qty*price+fee(remaining_qty*price, 'buy', **costs) if remaining_qty else 0.
|
|||
|
|
else:
|
|||
|
|
desired = per_new
|
|||
|
|
budget = min(available, desired)
|
|||
|
|
qty = buy_qty(c, price, budget, costs)
|
|||
|
|
if phase == 'entering_micro':
|
|||
|
|
qty = min(qty, remaining_qty)
|
|||
|
|
if qty:
|
|||
|
|
result.append({'book_id': 'micro30', 'ts_code': c, 'side': 'buy', 'qty': qty, 'reason': '初始建仓补齐' if phase == 'entering_micro' else '名单调入'})
|
|||
|
|
available -= qty*price+fee(qty*price, 'buy', **costs)
|
|||
|
|
return result, waits
|
|||
|
|
|
|||
|
|
|
|||
|
|
def apply_paper_fill(account, order, price, trade_date, costs, prices=None):
|
|||
|
|
"""独立纸面现金账,不接真实成交。相同成交键只记一次,T+1按买入日约束。"""
|
|||
|
|
key = order['id']
|
|||
|
|
if key in account['fills']:
|
|||
|
|
return False
|
|||
|
|
book, code, side, qty = order['book_id'], order['ts_code'], order['side'], order['qty']
|
|||
|
|
positions = account['books'][book]
|
|||
|
|
position = positions.setdefault(code, {'qty': 0, 'cost': 0., 'lots': []})
|
|||
|
|
amount = qty*price
|
|||
|
|
fees = fee(amount, side, **costs)
|
|||
|
|
from app.core import rotation_account as capital
|
|||
|
|
values = {}
|
|||
|
|
prices = prices or {code: price}
|
|||
|
|
for b in ('original', 'micro30'):
|
|||
|
|
if any(c not in prices for c, p in account['books'][b].items() if p['qty']):
|
|||
|
|
raise ValueError('纸面划拨前需要完整持仓估值')
|
|||
|
|
values[b] = sum(p['qty']*prices.get(c, 0) for c, p in account['books'][b].items())
|
|||
|
|
if 'capital' not in account:
|
|||
|
|
account['capital'] = capital.seed(account['cash'], values)
|
|||
|
|
cashbook = account['capital']
|
|||
|
|
if side == 'buy':
|
|||
|
|
if account['cash']+1e-8 < amount+fees:
|
|||
|
|
raise ValueError('纸面账户现金不足')
|
|||
|
|
need = max(0., amount+fees-cashbook['cash'][book])
|
|||
|
|
if need:
|
|||
|
|
capital.transfer(cashbook, 'original' if book == 'micro30' else 'micro30', book, need, values, 'fund:'+key)
|
|||
|
|
capital.fill(cashbook, book, side, amount, fees, key)
|
|||
|
|
account['cash'] -= amount+fees
|
|||
|
|
position['qty'] += qty
|
|||
|
|
position['cost'] += amount+fees
|
|||
|
|
position['lots'].append({'date': trade_date, 'qty': qty})
|
|||
|
|
else:
|
|||
|
|
available = sum(r['qty'] for r in position['lots'] if r['date'] < trade_date)
|
|||
|
|
if qty > available or qty > position['qty']:
|
|||
|
|
raise ValueError('纸面账本可卖数量不足')
|
|||
|
|
capital.fill(cashbook, book, side, amount, fees, key)
|
|||
|
|
old_qty = position['qty']
|
|||
|
|
position['qty'] -= qty
|
|||
|
|
released_cost = position['cost']*qty/old_qty
|
|||
|
|
position['cost'] -= released_cost
|
|||
|
|
account['cash'] += amount-fees
|
|||
|
|
account['realized'][book] += amount-fees-released_cost
|
|||
|
|
remaining = qty
|
|||
|
|
for lot in position['lots']:
|
|||
|
|
taken = min(remaining, lot['qty']) if lot['date'] < trade_date else 0
|
|||
|
|
lot['qty'] -= taken
|
|||
|
|
remaining -= taken
|
|||
|
|
account['fees'][book] += fees
|
|||
|
|
account['fills'][key] = {**order, 'price': price, 'date': trade_date, 'fee': fees}
|
|||
|
|
return True
|