111 lines
5.7 KiB
Python
111 lines
5.7 KiB
Python
"""建仓资金预算。金额与股数分开保存;预算不因取整、报价或重评而增加。"""
|
||
from decimal import Decimal, InvalidOperation, ROUND_FLOOR
|
||
from hashlib import sha256
|
||
import json
|
||
from app.core.sizer import lot_of
|
||
|
||
VERSION = 1
|
||
|
||
|
||
def number(value, label, *, zero=False):
|
||
try:
|
||
result = Decimal(str(value))
|
||
except (InvalidOperation, ValueError, TypeError):
|
||
raise ValueError(label+'不可核实') from None
|
||
if not result.is_finite() or (result < 0 if zero else result <= 0):
|
||
raise ValueError(label+'不可核实')
|
||
return result
|
||
|
||
|
||
def quantity(amount, price, code):
|
||
value = int((number(amount, '剩余预算', zero=True) / number(price, '买入价格') / 100).to_integral_value(rounding=ROUND_FLOOR)) * 100
|
||
return value if value >= lot_of(code) else 0
|
||
|
||
|
||
def identity(value):
|
||
body = {k: v for k, v in value.items() if k != 'revision'}
|
||
return sha256(json.dumps(body, sort_keys=True, ensure_ascii=False, allow_nan=False).encode()).hexdigest()[:24]
|
||
|
||
|
||
def validate(value, code):
|
||
if not isinstance(value, dict) or value.get('version') != VERSION or value.get('ts_code') != code:
|
||
raise ValueError('建仓预算版本或证券不一致,等待核实')
|
||
number(value.get('amount'), '原建仓预算')
|
||
number(value.get('scale'), '原建仓规模')
|
||
number(value.get('target_pct'), '原目标比例')
|
||
q = number(value.get('quantity_limit'), '计划数量', zero=True)
|
||
if q != int(q) or int(q) % 100 or value.get('revision') != identity(value):
|
||
raise ValueError('建仓预算内容已变化,等待重新核实')
|
||
return value
|
||
|
||
|
||
def resize(advice, hard, code):
|
||
"""返回完整重算结果;数量0是明确不建仓,必要读数缺失则抛错。"""
|
||
from app.core.execution_policy import supported_code
|
||
if not supported_code(code):
|
||
raise ValueError('建仓预算只适用于沪深合资格证券')
|
||
price = number(hard.get('price'), '买入价格')
|
||
pct = number(advice.get('target_pct'), '目标比例')
|
||
if pct > 1:
|
||
raise ValueError('目标比例超出有效范围,暂不建仓')
|
||
if advice.get('tier') == '试探仓':
|
||
# 旧 force_trial 只换标签,曾保留标准仓比例;按保存的原机械比例核实。
|
||
mechanical = number((advice.get('mechanical') or {}).get('target_pct'), '原机械目标比例')
|
||
pct = min(pct, mechanical / 6)
|
||
old = hard.get('buy_budget')
|
||
if old is not None:
|
||
validate(old, code)
|
||
scale = number(old['scale'], '原建仓规模')
|
||
amount = min(number(old['amount'], '原建仓预算'), scale * pct)
|
||
else:
|
||
scale = (number(hard['sizing_scale'], '原建仓规模') if hard.get('sizing_scale') is not None
|
||
else number(hard.get('target_amount'), '目标金额') / number(hard.get('target_pct'), '原目标比例'))
|
||
amount = scale * pct
|
||
amount = amount.quantize(Decimal('.01'), rounding=ROUND_FLOOR)
|
||
if amount <= 0:
|
||
raise ValueError('建仓预算不足一分钱,暂不建仓')
|
||
trial = advice.get('tier') == '试探仓' or (old and old.get('tier') == '试探仓')
|
||
splits = (1.0,) if trial else tuple(advice.get('splits') or (1.0,))
|
||
ratios = [number(v, '分批比例') for v in splits]
|
||
if abs(sum(ratios)-1) > Decimal('.00000001'):
|
||
raise ValueError('分批比例不完整,暂不建仓')
|
||
quantities = [quantity(amount*r, price, code) for r in ratios]
|
||
# 沿用总体设计的合批阶梯;只改变分批,不扩大本次批准金额。
|
||
merged = False
|
||
merge = bool((old or {}).get('min_lot_merge', hard.get('min_lot_merge', True)))
|
||
if not all(quantities) and merge and not trial:
|
||
from app.core.sizer import MERGE_LADDER
|
||
for _, alternate in MERGE_LADDER[1:]:
|
||
if len(alternate) >= len(splits):
|
||
continue
|
||
counts = [quantity(amount*number(r, '分批比例'), price, code) for r in alternate]
|
||
if all(counts):
|
||
splits, quantities, merged = alternate, counts, True
|
||
break
|
||
executable = all(quantities)
|
||
first = quantities[0] if executable else 0
|
||
maximum = sum(quantities) if executable else 0
|
||
budget = {'version': VERSION, 'ts_code': code, 'amount': str(amount), 'scale': str(scale),
|
||
'target_pct': str(amount/scale), 'quantity_limit': maximum,
|
||
'tier': old['tier'] if old and old.get('tier') == '试探仓' else advice.get('tier'),
|
||
'min_lot_merge': merge,
|
||
'basis': '买入成交金额,不含另记的交易费用'}
|
||
budget['revision'] = identity(budget)
|
||
minimum_amount = price * lot_of(code)
|
||
reason = '' if first else f'当前预算{amount:.2f}元不足分批最低买入量,暂不建仓(每批最低{lot_of(code)}股,需{minimum_amount:.2f}元)'
|
||
if merged:
|
||
reason = '原分批不足最低买入量,已在原预算内合并为' + '/'.join(f'{v:.0%}' for v in splits)
|
||
return {'qty': first, 'target_pct': float(amount/scale), 'target_amount': float(amount),
|
||
'minimum_order_amount': float(minimum_amount),
|
||
'base_amount': float(first*price), 'batch_scheme': ','.join(str(v) for v in splits),
|
||
'buy_budget': budget, 'note': reason}
|
||
|
||
|
||
def check_quantity(budget, code, qty, price):
|
||
validate(budget, code)
|
||
count = number(qty, '计划数量')
|
||
if count != int(count) or int(count) % 100 or int(count) < lot_of(code):
|
||
raise ValueError('预算内数量不足最低买入量,暂不建仓')
|
||
if count > int(budget['quantity_limit']) or count*number(price, '买入价格') > number(budget['amount'], '原建仓预算'):
|
||
raise ValueError('计划数量或金额超过原建仓预算,需重新明确预算后再参与')
|