"""成交更正纯投影专项。只用虚构逐笔与批次,经统一护栏断网执行。""" import unit_test_guard # noqa: F401 import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from copy import deepcopy from datetime import datetime, timezone, timedelta from decimal import Decimal, ROUND_HALF_UP import unittest from app.core.trade_correction import compile_correction CODE, TODAY = '600001.SH', '2026-11-05' TZ = timezone(timedelta(hours=8)) def economic(qty, price): return {'qty': qty, 'price': str(price), 'amount': format( (Decimal(str(price)) * qty).quantize(Decimal('.01'), rounding=ROUND_HALF_UP), 'f')} def trade(no, seq, side, qty, price, *, day=TODAY, parent=None, book='original'): at = datetime.fromisoformat(day + 'T10:00:00+08:00') + timedelta(minutes=seq) payload = dict(economic(qty, price), trade_no=no, ts_code=CODE, side=side, instruction_id=(parent or 'P_'+no)+'_D01', parent_id=parent or 'P_'+no, broker_order_id='BROKER_'+no, trade_time=int(at.timestamp()*1000), fee=None) return {'seq': seq, 'payload': payload, 'original_payload': deepcopy(payload), 'processed_at': at.isoformat(), 'book_day': day, 'book_id': book} def lot(row, lid=1, *, qty=None, closed=0, close=None, pnl='0.00', kind='BASE', book='original'): p = row['payload'] qty = p['qty'] - closed if qty is None else qty return {'id': lid, 'book_id': book, 'ts_code': p['ts_code'], 'instruction_id': p['parent_id'], 'open_date': row['book_day'], 'created_at': row['processed_at'], 'lot_type': kind, 'qty': qty, 'closed_qty': closed, 'open_price': p['price'], 'close_avg_price': close, 'realized_pnl': pnl, 'status': 'OPEN' if qty else 'CLOSED'} def fixture(sold=False): """服务层可复用的最小合法输入;100股买入,或随后40股卖出。""" buy = trade('BUY', 1, 'buy', 100, '10.000') if not sold: return {'lots': [lot(buy)], 'trades': [buy]} sell = trade('SELL', 2, 'sell', 40, '12.000') return {'lots': [lot(buy, closed=40, close='12.000', pnl='80.00')], 'trades': [buy, sell]} class ProjectionTests(unittest.TestCase): def compile(self, data=None, target='BUY', qty=100, price='11.000', **kwargs): return compile_correction(**(data or fixture()), target_trade_no=target, after=economic(qty, price), today=kwargs.pop('today', TODAY), **kwargs) def test_buy_price_updates_cost_and_cash_without_qty_or_avail(self): out = self.compile() self.assertEqual((out['qty_before'], out['qty_after'], out['cash_delta'], out['avail_delta']), (100, 100, '-100.00', 0)) self.assertEqual(out['lots'][0]['open_price'], '11.000') self.assertEqual(Decimal(out['net_cost_after']), Decimal('1100')) def test_buy_quantity_grows_current_day_holding_without_sellable(self): out = self.compile(qty=150, price='10') self.assertEqual((out['qty_after'], out['avail_delta'], out['cash_delta']), (150, 0, '-500.00')) def test_buy_quantity_reduction_refunds_only_principal(self): out = self.compile(qty=60, price='10') self.assertEqual((out['qty_after'], out['cash_delta']), (60, '400.00')) def test_zero_buy_keeps_closed_lot_and_source_metadata(self): data = fixture(); old = deepcopy(data) out = self.compile(data, qty=0, price='0') self.assertEqual((len(out['lots']), out['lots'][0]['id'], out['lots'][0]['status']), (1, 1, 'CLOSED')) self.assertEqual((out['lots'][0]['qty'], out['cash_delta']), (0, '1000.00')) self.assertEqual(out['lots'][0]['created_at'], old['lots'][0]['created_at']) self.assertEqual(data, old) def test_later_sell_is_reallocated_after_buy_price_correction(self): out = self.compile(fixture(True)) self.assertEqual((out['lots'][0]['qty'], out['lots'][0]['closed_qty']), (60, 40)) self.assertEqual(out['lots'][0]['realized_pnl'], '40.00') self.assertEqual(Decimal(out['net_cost_after']), Decimal('620')) self.assertEqual(out['allocations'][0]['realized_pnl_delta'], '40.00') def test_sell_price_corrects_closed_cost_and_cash(self): out = self.compile(fixture(True), target='SELL', qty=40, price='13') self.assertEqual((out['lots'][0]['close_avg_price'], out['lots'][0]['realized_pnl']), ('13.000', '120.00')) self.assertEqual((out['cash_delta'], out['avail_delta']), ('40.00', 0)) def test_sell_quantity_corrects_position_and_sellable(self): out = self.compile(fixture(True), target='SELL', qty=50, price='12') self.assertEqual((out['qty_after'], out['avail_delta'], out['cash_delta']), (50, -10, '120.00')) self.assertEqual(out['lots'][0]['realized_pnl'], '100.00') def test_zero_sell_restores_original_lot_without_new_buy(self): out = self.compile(fixture(True), target='SELL', qty=0, price='0') self.assertEqual((out['qty_after'], out['avail_delta'], out['cash_delta']), (100, 40, '-480.00')) self.assertEqual((out['lots'][0]['closed_qty'], out['lots'][0]['close_avg_price']), (0, None)) def test_correction_cannot_oversell_at_any_intermediate_step(self): with self.assertRaises(ValueError): self.compile(fixture(True), qty=30, price='10') with self.assertRaises(ValueError): self.compile(fixture(True), target='SELL', qty=101, price='12') def test_allocation_keeps_original_tier_and_add_date_order(self): rows = [trade('BASE', 1, 'buy', 100, 10, day='2026-11-03'), trade('T', 2, 'buy', 100, 11, day='2026-11-03'), trade('OLD', 3, 'buy', 100, 12, day='2026-11-03'), trade('NEW', 4, 'buy', 100, 13, day='2026-11-04'), trade('SELL', 5, 'sell', 250, 14)] lots = [lot(rows[0]), lot(rows[1], 2, closed=100, close='14', pnl='300', kind='T0'), lot(rows[2], 3, closed=50, close='14', pnl='100', kind='ADD'), lot(rows[3], 4, closed=100, close='14', pnl='100', kind='ADD')] out = self.compile({'lots': lots, 'trades': rows}, target='SELL', qty=350, price='14') self.assertEqual([(a['lot_id'], a['qty']) for a in out['allocations']], [(2, 100), (4, 100), (3, 100), (1, 50)]) self.assertEqual(out['qty_after'], 50) def test_closed_lot_sell_price_can_be_projected_without_reopening(self): data = fixture(True) data['trades'][1] = trade('SELL', 2, 'sell', 100, 12) data['lots'][0] = lot(data['trades'][0], closed=100, close='12', pnl='200') out = self.compile(data, target='SELL', qty=100, price='11') self.assertEqual((out['qty_after'], out['lots'][0]['status'], out['lots'][0]['realized_pnl']), (0, 'CLOSED', '100.00')) def closed_round_with_new_buy(self): buy, sell = trade('BUY', 1, 'buy', 100, 10), trade('SELL', 2, 'sell', 100, 12) new = trade('NEW', 3, 'buy', 100, 10) return {'lots': [lot(buy, closed=100, close='12', pnl='200'), lot(new, 2)], 'trades': [buy, sell, new]} def test_old_round_price_correction_cannot_change_new_holding_cost(self): data = self.closed_round_with_new_buy() for target, qty, price in (('BUY', 100, '11'), ('SELL', 100, '13')): with self.subTest(target=target), self.assertRaisesRegex(ValueError, '清零并建立新仓'): self.compile(data, target=target, qty=qty, price=price) def test_quantity_correction_cannot_carry_old_inventory_into_new_round(self): data = self.closed_round_with_new_buy() for target, qty, price in (('BUY', 150, '10'), ('SELL', 50, '12')): with self.subTest(target=target), self.assertRaisesRegex(ValueError, '人工核对'): self.compile(data, target=target, qty=qty, price=price) def test_latest_round_correction_keeps_prior_closed_round_unchanged(self): data = self.closed_round_with_new_buy() out = self.compile(data, target='NEW') self.assertEqual(out['lots'][0]['realized_pnl'], '200.00') self.assertEqual([r['id'] for r in out['changes']], [2]) self.assertEqual((out['qty_after'], out['cash_delta']), (100, '-100.00')) def test_zeroed_old_buy_cannot_be_revived_into_later_new_round(self): data = fixture(); zero = self.compile(data, qty=0, price='0') data['lots'] = zero['lots']; data['trades'][0]['payload'].update(zero['trade_after']) new = trade('NEW', 2, 'buy', 100, 10) data['lots'].append(lot(new, 2)); data['trades'].append(new) with self.assertRaisesRegex(ValueError, '清零并建立新仓'): self.compile(data, qty=50, price='10', lot_links={'BUY': 1, 'NEW': 2}) def test_tomorrow_buy_quantity_change_is_sellable(self): out = self.compile(qty=150, price='10', today='2026-11-06') self.assertEqual(out['avail_delta'], 50) def test_previous_day_sell_delta_still_reduces_today_sellable(self): out = self.compile(fixture(True), target='SELL', qty=50, price='12', today='2026-11-06') self.assertEqual(out['avail_delta'], -10) def test_cross_day_booked_quantity_needs_verified_t_plus_one(self): data = fixture(); data['lots'][0]['open_date'] = '2026-11-06' with self.assertRaises(ValueError): self.compile(data, qty=150, price='10', today='2026-11-06') self.assertEqual(self.compile(data, today='2026-11-06')['avail_delta'], 0) data = fixture(True); data['trades'][1]['book_day'] = '2026-11-06' with self.assertRaises(ValueError): self.compile(data, target='SELL', qty=50, price='12', today='2026-11-06') def test_missing_or_future_actual_trade_day_is_not_inferred(self): data = fixture(); data['trades'][0]['original_payload'].pop('trade_time') with self.assertRaises(ValueError): self.compile(data) data['trades'][0]['trade_day'] = TODAY self.assertEqual(self.compile(data)['qty_after'], 100) with self.assertRaises(ValueError): self.compile(today='2026-11-04') def test_same_code_other_strategy_is_rejected(self): data = fixture(); data['lots'][0]['book_id'] = 'micro30' with self.assertRaises(ValueError): self.compile(data) data['trades'][0]['book_id'] = 'micro30' self.assertEqual(self.compile(data)['lots'][0]['book_id'], 'micro30') def test_chain_uses_effective_trade_and_persisted_lineage(self): data = fixture(True); first = self.compile(data) data['lots'] = first['lots'] data['trades'][0]['payload'].update(first['trade_after']) out = self.compile(data, qty=110, price='11', lot_links=first['lot_links']) self.assertEqual((out['qty_after'], out['amount_before'], out['cash_delta']), (70, '1100.00', '-110.00')) self.assertEqual(data['trades'][0]['original_payload']['price'], '10.000') with self.assertRaises(ValueError): self.compile(data, qty=110, price='11') def test_chain_can_correct_zeroed_trade_without_deleting_its_identity(self): data = fixture(); first = self.compile(data, qty=0, price='0') data['lots'] = first['lots'] data['trades'][0]['payload'].update(first['trade_after']) out = self.compile(data, qty=50, price='10', lot_links=first['lot_links']) self.assertEqual((out['qty_before'], out['qty_after'], out['cash_delta']), (0, 50, '-500.00')) self.assertEqual(out['lots'][0]['id'], 1) def test_ambiguous_legacy_lot_needs_explicit_mapping(self): a = trade('A', 1, 'buy', 100, 10, parent='P') b = trade('B', 2, 'buy', 100, 10, parent='P'); b['processed_at'] = a['processed_at'] data = {'lots': [lot(a), lot(b, 2)], 'trades': [a, b]} with self.assertRaises(ValueError): self.compile(data, target='A') out = self.compile(data, target='A', lot_links={'A': 1, 'B': 2}) self.assertEqual(out['lots'][1]['open_price'], '10.000') with self.assertRaises(ValueError): self.compile(data, target='A', lot_links={'A': 1, 'B': 1}) def test_explicit_mapping_cannot_cross_parent_or_missing_lot(self): for links in ({'BUY': 999}, {'OTHER': 1}): with self.assertRaises(ValueError): self.compile(lot_links=links) data = fixture(); data['lots'][0]['instruction_id'] = 'OTHER' with self.assertRaises(ValueError): self.compile(data, lot_links={'BUY': 1}) def test_recon_external_and_archived_evidence_are_rejected(self): for patch in ({'lot_type': 'RECON'}, {'lot_type': 'UNKNOWN'}, {'instruction_id': None}, {'archived_at': '2026-11-05 11:00:00'}): with self.subTest(patch=patch): data = fixture(); data['lots'][0].update(patch) with self.assertRaises(ValueError): self.compile(data) def test_unexplained_lot_or_missing_trade_blocks_zero_baseline(self): data = fixture(); data['lots'].append(dict(data['lots'][0], id=2, instruction_id='EXTERNAL')) with self.assertRaises(ValueError): self.compile(data) data = fixture(True); data['trades'] = data['trades'][1:] with self.assertRaises(ValueError): self.compile(data, target='SELL', qty=40, price='13') def test_original_projection_must_match_all_persisted_fields(self): for patch in ({'qty': 61}, {'closed_qty': 39}, {'open_price': '9'}, {'close_avg_price': '11.999'}, {'realized_pnl': '79.99'}, {'status': 'CLOSED'}): with self.subTest(patch=patch): data = fixture(True); data['lots'][0].update(patch) with self.assertRaises(ValueError): self.compile(data, lot_links={'BUY': 1}) def test_duplicate_trade_number_or_seq_and_identity_change_block(self): for kind in ('trade_no', 'seq', 'identity'): data = fixture(True) if kind == 'seq': data['trades'][1]['seq'] = 1 elif kind == 'trade_no': for field in ('payload', 'original_payload'): data['trades'][1][field]['trade_no'] = 'BUY' else: data['trades'][0]['payload']['side'] = 'sell' with self.assertRaises(ValueError): self.compile(data) def test_other_code_and_beijing_exchange_never_enter_projection(self): for code in ('600002.SH', '430001.BJ', '600001.SZ'): data = fixture(); data['lots'][0]['ts_code'] = code with self.assertRaises(ValueError): self.compile(data) def test_invalid_after_values_and_identity_or_fee_changes_block(self): cases = [dict(qty=-1, price='10', amount='0'), dict(qty=True, price='10', amount='10'), dict(qty=1.5, price='10', amount='15'), dict(qty=100, price='NaN', amount='0'), dict(qty=100, price='Infinity', amount='0'), dict(qty=1, price='10.0001', amount='10'), dict(qty=100, price='11', amount='1099.99'), dict(qty=0, price='0', amount='1'), dict(qty=100, price='11', amount='1100', side='sell'), dict(qty=100, price='11', amount='1100', fee='1')] for value in cases: with self.subTest(value=value), self.assertRaises(ValueError): compile_correction(**fixture(), target_trade_no='BUY', after=value, today=TODAY) def test_odd_share_and_half_cent_keep_price_precision_and_money_rounding(self): buy = trade('BUY', 1, 'buy', 1, '48.285') out = self.compile({'lots': [lot(buy)], 'trades': [buy]}, qty=1, price='48.295') self.assertEqual((out['lots'][0]['open_price'], out['amount_before'], out['amount_after']), ('48.295', '48.29', '48.30')) self.assertEqual(out['cash_delta'], '-0.01') def test_realized_pnl_rounds_after_each_sell_not_only_at_end(self): buy = trade('BUY', 1, 'buy', 3, '10') a, b = trade('S1', 2, 'sell', 1, '10.005'), trade('S2', 3, 'sell', 1, '10.005') data = {'lots': [lot(buy, closed=2, close='10.005', pnl='.02')], 'trades': [buy, a, b]} out = self.compile(data, target='S2', qty=1, price='10.015') self.assertEqual(out['lots'][0]['realized_pnl'], '0.03') self.assertEqual([r['realized_pnl_delta'] for r in out['allocations']], ['0.01', '0.02']) def test_close_average_uses_previous_stored_three_decimals(self): buy = trade('BUY', 1, 'buy', 4, 10) rows = [buy, trade('S1', 2, 'sell', 1, '10.001'), trade('S2', 3, 'sell', 2, '10.002'), trade('S3', 4, 'sell', 1, '10.000')] data = {'lots': [lot(buy, closed=4, close='10.002', pnl='0')], 'trades': rows} out = self.compile(data, target='S3', qty=1, price='10.004') self.assertEqual(out['lots'][0]['close_avg_price'], '10.003') def test_t_profit_rounds_whole_sell_separately_from_each_lot(self): a, b = trade('A', 1, 'buy', 1, '10.005'), trade('B', 2, 'buy', 1, '10.005') sell = trade('S', 3, 'sell', 2, '10.010') data = {'lots': [lot(a, closed=1, close='10.010', pnl='.01', kind='T0'), lot(b, 2, closed=1, close='10.010', pnl='.01', kind='T0')], 'trades': [a, b, sell]} out = self.compile(data, target='S', qty=2, price='10.020') self.assertEqual((out['t_profit_before'], out['t_profit_after'], out['t_profit_delta']), ('0.01', '0.03', '0.02')) self.assertEqual(sum(Decimal(l['realized_pnl']) for l in out['lots']), Decimal('.04')) def test_inputs_are_unchanged_and_unsorted_input_is_deterministic(self): data = fixture(True); before = deepcopy(data) one = self.compile(data) self.assertEqual(data, before) data['trades'].reverse() self.assertEqual(one, self.compile(data)) def test_bigint_lineage_ids_are_not_limited_to_trade_quantity_range(self): data = fixture(); data['lots'][0]['id'] = 2**32; data['trades'][0]['seq'] = 2**32 self.assertEqual(self.compile(data)['lots'][0]['id'], 2**32) if __name__ == '__main__': unittest.main()