211 lines
10 KiB
Python
211 lines
10 KiB
Python
"""策略估值缺行情时保留现金和数量核验,资金动作继续严格阻断。"""
|
||
import unit_test_guard # noqa: F401
|
||
import copy
|
||
import datetime as dt
|
||
from contextlib import contextmanager, nullcontext
|
||
from pathlib import Path
|
||
import sys
|
||
import unittest
|
||
from unittest.mock import patch
|
||
|
||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||
from app.core import rotation_account as core, strategy_book as books
|
||
from app.services import rotation_accounting as accounting, rotation_service as rotation
|
||
|
||
|
||
def held(code='002979.SZ', book='original', qty=100, cost=48.296):
|
||
return {'book_id': book, 'ts_code': code, 'total_qty': qty, 'avg_cost': cost}
|
||
|
||
|
||
class AccountingTests(unittest.TestCase):
|
||
def setUp(self):
|
||
self.capital = core.seed(10000, {'original': 0, 'micro30': 0})
|
||
self.capital['started_at'] = '2026-11-03T15:00:00+08:00'
|
||
for obj, name, kw in (
|
||
(accounting.store, 'get', {'return_value': (self.capital, 1)}),
|
||
(accounting.pms_repo, 'list_positions', {'return_value': [held()]}),
|
||
(accounting.market, 'day_snapshot', {'return_value': {}}),
|
||
(accounting.qmt_repo, 'latest_snapshot', {'return_value': {
|
||
'age_sec': 5, 'seq': 10, 'payload': {'available_cash': 9000, 'frozen_cash': 1000}}}),
|
||
):
|
||
p = patch.object(obj, name, **kw)
|
||
setattr(self, name, p.start())
|
||
self.addCleanup(p.stop)
|
||
|
||
def test_missing_quote_preserves_cash_cost_quantity_and_cash_reconciliation(self):
|
||
value = accounting.view()
|
||
self.assertFalse(value['ready'])
|
||
self.assertTrue(value['cash_ready'])
|
||
self.assertFalse(value['valuation_ready'])
|
||
self.assertEqual(value['valuation_missing'], ['002979.SZ'])
|
||
self.assertEqual(value['cash_difference'], 0)
|
||
self.assertEqual(value['metrics']['account']['cash'], 10000)
|
||
self.assertEqual(value['positions'][0]['qty'], 100)
|
||
self.assertAlmostEqual(value['positions'][0]['cost'], 4829.6)
|
||
self.assertIsNone(value['positions'][0]['price'])
|
||
self.assertIsNone(value['positions'][0]['market_value'])
|
||
self.assertIn('等待行情', value['reason'])
|
||
|
||
def test_missing_quote_does_not_publish_zero_valuation_or_false_loss(self):
|
||
value = accounting.view()
|
||
for book in ('original', 'account'):
|
||
for key in ('market_value', 'equity', 'profit'):
|
||
self.assertIsNone(value['metrics'][book][key])
|
||
self.assertIsNone(value['metrics']['original']['nav'])
|
||
self.assertEqual(value['metrics']['micro30']['market_value'], 0)
|
||
|
||
def test_only_affected_book_loses_valuation(self):
|
||
self.list_positions.return_value = [held(), held('600000.SH', 'micro30', cost=10)]
|
||
self.day_snapshot.side_effect = lambda c: {} if c == '002979.SZ' else {'price': 11.}
|
||
value = accounting.view()
|
||
self.assertIsNone(value['metrics']['original']['equity'])
|
||
self.assertEqual(value['metrics']['micro30']['equity'], 1100)
|
||
self.assertIsNone(value['metrics']['account']['equity'])
|
||
|
||
def test_same_book_quote_order_does_not_hide_missing_position(self):
|
||
for rows in ([held(), held('600000.SH')], [held('600000.SH'), held()]):
|
||
self.list_positions.return_value = rows
|
||
self.day_snapshot.side_effect = lambda c: {} if c == '002979.SZ' else {'price': 11.}
|
||
value = accounting.view()
|
||
self.assertIsNone(value['metrics']['original']['market_value'])
|
||
self.assertEqual(len(value['positions']), 2)
|
||
|
||
def test_quote_recovery_restores_complete_valuation_without_restart(self):
|
||
self.assertFalse(accounting.view()['ready'])
|
||
self.day_snapshot.return_value = {'price': 49.}
|
||
value = accounting.view()
|
||
self.assertTrue(value['ready'])
|
||
self.assertTrue(value['valuation_ready'])
|
||
self.assertEqual(value['valuation_missing'], [])
|
||
self.assertEqual(value['metrics']['original']['market_value'], 4900)
|
||
self.assertEqual(value['metrics']['account']['equity'], 14900)
|
||
self.assertIsNone(value['reason'])
|
||
|
||
def test_invalid_prices_remain_missing_and_json_safe(self):
|
||
for price in (None, 0, -1, float('nan'), float('inf'), 'bad', True):
|
||
self.day_snapshot.return_value = {'price': price}
|
||
value = accounting.view()
|
||
self.assertFalse(value['ready'], repr(price))
|
||
self.assertIsNone(value['positions'][0]['price'])
|
||
self.assertIsNone(value['metrics']['account']['equity'])
|
||
|
||
def test_empty_position_book_has_known_zero_market_value(self):
|
||
self.list_positions.return_value = []
|
||
value = accounting.view()
|
||
self.assertTrue(value['ready'])
|
||
self.assertEqual(value['metrics']['account']['equity'], 10000)
|
||
self.day_snapshot.assert_not_called()
|
||
|
||
def test_strict_marked_values_still_reject_missing_quote(self):
|
||
with self.assertRaisesRegex(ValueError, '策略估值行情缺失:002979.SZ'):
|
||
accounting.marked_values()
|
||
|
||
def test_reservation_cannot_transfer_cash_without_complete_valuation(self):
|
||
before = copy.deepcopy(self.capital)
|
||
|
||
@contextmanager
|
||
def locked(*args, **kwargs):
|
||
yield self.capital
|
||
|
||
with patch.object(accounting.store, 'locked', side_effect=locked), \
|
||
patch.object(accounting.store, 'put_once') as write:
|
||
with self.assertRaisesRegex(ValueError, '策略估值行情缺失'):
|
||
accounting.reserve_book('micro30', 100, [], 'entering_micro')
|
||
write.assert_not_called()
|
||
self.assertEqual(self.capital, before)
|
||
|
||
def test_unknown_pure_valuation_rejects_transfer_before_mutation(self):
|
||
before = copy.deepcopy(self.capital)
|
||
with self.assertRaisesRegex(ValueError, '估值不完整'):
|
||
core.transfer(self.capital, 'original', 'micro30', 100,
|
||
{'original': 0., 'micro30': None}, 'key')
|
||
self.assertEqual(self.capital, before)
|
||
|
||
def test_initialization_cannot_seed_unknown_valuation_as_zero(self):
|
||
from app.db import session as db
|
||
self.get.return_value = (None, 0)
|
||
self.latest_snapshot.return_value['payload']['frozen_cash'] = 0
|
||
with patch.object(accounting.store, 'account_guard', side_effect=nullcontext), \
|
||
patch.object(db, 'fetch_all', return_value=[]), \
|
||
patch.object(rotation, 'reconcile_books', return_value={'ok': True}), \
|
||
patch.object(accounting.store, 'put_once') as write:
|
||
with self.assertRaisesRegex(ValueError, '策略估值行情缺失'):
|
||
accounting.initialize()
|
||
write.assert_not_called()
|
||
|
||
def test_missing_quote_never_loads_cost_or_daily_close_as_price(self):
|
||
with patch.object(accounting.market, 'get_last_close') as close, \
|
||
patch.object(accounting.market, 'get_prev_close') as previous:
|
||
accounting.view()
|
||
close.assert_not_called()
|
||
previous.assert_not_called()
|
||
|
||
def test_stale_funds_do_not_fake_cash_reconciliation(self):
|
||
self.latest_snapshot.return_value['age_sec'] = 61
|
||
self.assertIsNone(accounting.view()['cash_difference'])
|
||
|
||
def test_no_capital_still_reports_uninitialized(self):
|
||
self.get.return_value = (None, 0)
|
||
value = accounting.view()
|
||
self.assertFalse(value['ready'])
|
||
self.assertIn('尚未初始化', value['reason'])
|
||
self.list_positions.assert_not_called()
|
||
|
||
|
||
class StatusTests(unittest.TestCase):
|
||
def setUp(self):
|
||
config = {'mode': 'auto', 'control': 'run', 'rule_version': rotation.core.RULE,
|
||
'boards': set(), 'costs': {}, 'candidate_pool_size': 100}
|
||
for obj, name, kw in (
|
||
(rotation, 'configuration', {'return_value': config}),
|
||
(rotation, 'pull', {'return_value': {}}),
|
||
(rotation, 'documents_ready', {'return_value': True}),
|
||
(rotation.settings, 'INFRA_STRATEGY_BOOK_SCHEMA', {'new': True}),
|
||
(rotation.settings, 'PMS_TABLE_PREFIX', {'new': ''}),
|
||
(rotation.store, 'get', {'return_value': (None, 0)}),
|
||
(rotation.store, 'recent', {'return_value': []}),
|
||
(rotation, 'activation_errors', {'return_value': []}),
|
||
(rotation.param_store, 'get_bool', {'return_value': False}),
|
||
(rotation.param_store, 'get_float', {'return_value': 0}),
|
||
(rotation, 'reconcile_books', {'return_value': {'ok': True, 'diffs': []}}),
|
||
(accounting, 'view', {'return_value': {'ready': False, 'reason': '持仓估值等待行情:002979.SZ'}}),
|
||
):
|
||
p = patch.object(obj, name, **kw)
|
||
setattr(self, name, p.start())
|
||
self.addCleanup(p.stop)
|
||
|
||
def test_partial_valuation_keeps_independent_quantity_reconciliation(self):
|
||
value = rotation.status()
|
||
self.assertTrue(value['reconciliation']['ok'])
|
||
self.assertIn('持仓估值等待行情:002979.SZ', value['errors'])
|
||
self.assertFalse(any('ValueError' in e for e in value['errors']))
|
||
|
||
def test_accounting_error_does_not_skip_quantity_reconciliation(self):
|
||
self.view.side_effect = RuntimeError('internal details')
|
||
value = rotation.status()
|
||
self.reconcile_books.assert_called_once()
|
||
self.assertTrue(value['reconciliation']['ok'])
|
||
self.assertNotIn('internal details', str(value))
|
||
self.assertNotIn('RuntimeError', str(value))
|
||
|
||
def test_quantity_error_does_not_hide_accounting_or_claim_reconciliation(self):
|
||
self.reconcile_books.side_effect = ValueError('unsafe internal details')
|
||
value = rotation.status()
|
||
self.assertIn('accounting', value)
|
||
self.assertFalse(value['reconciliation']['ok'])
|
||
self.assertEqual(value['reconciliation']['severity'], 'ERROR')
|
||
self.assertNotIn('unsafe internal details', str(value))
|
||
self.assertNotIn('ValueError', str(value))
|
||
|
||
def test_incomplete_valuation_cannot_mark_daily_settlement_healthy(self):
|
||
with patch.object(rotation.td, 'calendar_degraded', return_value=False), \
|
||
patch.object(rotation.td, 'is_trade_day', return_value=True), \
|
||
patch.object(rotation.store, 'put_once') as put:
|
||
rotation.settle_day(dt.datetime(2026, 11, 4, 15, 30, tzinfo=rotation.TZ))
|
||
record = put.call_args.args[2]
|
||
self.assertFalse(record['healthy'])
|
||
|
||
|
||
if __name__ == '__main__':
|
||
unittest.main()
|