2026-10-26 16:24:14 +08:00
|
|
|
"""账户资金口径:防止回笼重复计入,账户展示与策略估值分开。"""
|
|
|
|
|
import unit_test_guard # noqa: F401
|
|
|
|
|
import os
|
|
|
|
|
import sys
|
|
|
|
|
import unittest
|
2026-11-09 10:27:11 +08:00
|
|
|
from unittest.mock import patch
|
2026-10-26 16:24:14 +08:00
|
|
|
|
|
|
|
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
2026-11-09 10:27:11 +08:00
|
|
|
from config.settings import settings
|
2026-11-10 12:06:38 +08:00
|
|
|
from app.core import rotation_account, strategy_book as books
|
2026-11-09 10:27:11 +08:00
|
|
|
from app.services import rotation_accounting
|
2026-10-26 16:24:14 +08:00
|
|
|
from app.core import rule_gate
|
|
|
|
|
from app.services import portfolio
|
|
|
|
|
from test_wiring import install_fakes
|
|
|
|
|
from test_batch3_units import ctx
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
FUNDS = dict(total_asset=1936261.62, available_cash=1806071.62,
|
|
|
|
|
frozen_cash=0.0, sell_return_today=1644823.13, market_value=130190.0)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class AccountFundsTest(unittest.TestCase):
|
|
|
|
|
def setUp(self):
|
|
|
|
|
self.fake = install_fakes(params={'PMS_TOTAL_SCALE': '2000000'})
|
|
|
|
|
|
|
|
|
|
def funds(self, **values):
|
|
|
|
|
data = dict(FUNDS, **values)
|
|
|
|
|
self.fake.qmt.put_snapshot(kind='funds', data=data)
|
|
|
|
|
return data
|
|
|
|
|
|
|
|
|
|
def gate(self, qty):
|
|
|
|
|
view = portfolio.positions_view()
|
|
|
|
|
caps = portfolio.caps_ctx(view, ts_code='600000.SH')
|
|
|
|
|
return rule_gate.check(side='buy', action='OPEN', qty=qty, price=10,
|
|
|
|
|
ctx=ctx(caps=caps))
|
|
|
|
|
|
|
|
|
|
def test_real_snapshot_sale_stat_does_not_create_extra_cash(self):
|
|
|
|
|
self.funds()
|
|
|
|
|
cash = portfolio.cash_view()
|
|
|
|
|
self.assertEqual(cash['cash_avail'], 1806071.62)
|
|
|
|
|
self.assertAlmostEqual(cash['cash_avail'] + cash['account_market_value'], cash['total_asset'])
|
|
|
|
|
|
|
|
|
|
def test_gate_rejects_order_only_affordable_with_double_count(self):
|
|
|
|
|
self.funds(available_cash=5000, sell_return_today=10000, total_asset=5000, market_value=0)
|
|
|
|
|
result = self.gate(1000)
|
|
|
|
|
self.assertFalse(result['passed'])
|
|
|
|
|
self.assertTrue(any(x.startswith('INSUFFICIENT_CASH:') for x in result['failed']))
|
|
|
|
|
self.assertEqual(result['hard_numbers']['cash_avail'], 5000)
|
|
|
|
|
|
|
|
|
|
def test_returned_sale_cash_remains_usable_in_reported_balance(self):
|
|
|
|
|
self.funds(available_cash=12000, sell_return_today=8000, total_asset=12000, market_value=0)
|
|
|
|
|
result = self.gate(1000)
|
|
|
|
|
self.assertTrue(result['passed'], result)
|
|
|
|
|
|
|
|
|
|
def test_zero_available_is_not_replaced_by_sale_stat(self):
|
|
|
|
|
self.funds(available_cash=0, sell_return_today=10000, total_asset=10000, frozen_cash=10000, market_value=0)
|
|
|
|
|
result = self.gate(100)
|
|
|
|
|
self.assertFalse(result['passed'])
|
|
|
|
|
self.assertEqual(result['hard_numbers']['cash_avail'], 0)
|
|
|
|
|
|
|
|
|
|
def test_frozen_cash_is_not_subtracted_twice(self):
|
|
|
|
|
self.funds(available_cash=8000, frozen_cash=2000, total_asset=10000, market_value=0)
|
|
|
|
|
result = self.gate(800)
|
|
|
|
|
self.assertTrue(result['passed'], result)
|
|
|
|
|
self.assertEqual(portfolio.overview()['frozen_cash'], 2000)
|
|
|
|
|
|
|
|
|
|
def test_missing_available_does_not_infer_cash_from_other_fields(self):
|
|
|
|
|
self.funds(available_cash=None)
|
|
|
|
|
cash = portfolio.cash_view()
|
|
|
|
|
self.assertEqual(cash['source'], 'estimate')
|
|
|
|
|
self.assertIsNone(cash['cash_avail'])
|
|
|
|
|
self.assertIsNone(cash['account_market_value'])
|
|
|
|
|
|
|
|
|
|
def test_stale_snapshot_does_not_masquerade_as_current_account(self):
|
|
|
|
|
self.fake.qmt.put_snapshot(kind='funds', data=FUNDS, age_sec=901)
|
|
|
|
|
result = portfolio.overview()
|
|
|
|
|
self.assertEqual(result['cash_source'], 'estimate')
|
|
|
|
|
for key in ('cash_avail', 'total_asset', 'account_market_value', 'frozen_cash'):
|
|
|
|
|
self.assertIsNone(result[key])
|
|
|
|
|
|
|
|
|
|
def test_account_display_does_not_change_strategy_valuation(self):
|
|
|
|
|
self.fake = install_fakes(prices={'002050.SZ': 34.41, '002518.SZ': 27.49, '688778.SH': 37.13},
|
|
|
|
|
positions=[{'ts_code': '002050.SZ', 'total_qty': 1800, 'avg_cost': 36.697},
|
|
|
|
|
{'ts_code': '002518.SZ', 'total_qty': 400, 'avg_cost': 27.549},
|
|
|
|
|
{'ts_code': '688778.SH', 'total_qty': 1400, 'avg_cost': 41.849}],
|
|
|
|
|
params={'PMS_TOTAL_SCALE': '2000000'})
|
|
|
|
|
self.funds()
|
|
|
|
|
result = portfolio.overview()
|
|
|
|
|
self.assertEqual(result['account_market_value'], 130190)
|
|
|
|
|
self.assertEqual(result['portfolio_mv'], 124916)
|
|
|
|
|
self.assertEqual(result['portfolio_pct'], 0.0625)
|
|
|
|
|
self.assertEqual(result['float_pnl'], -10746.8)
|
|
|
|
|
caps = portfolio.caps_ctx(portfolio.positions_view())
|
|
|
|
|
self.assertEqual(caps['portfolio_mv'], 124916)
|
|
|
|
|
self.assertEqual(caps['cash_avail'], 1806071.62)
|
|
|
|
|
|
|
|
|
|
def test_missing_account_value_is_not_replaced_by_market_estimate(self):
|
|
|
|
|
self.fake = install_fakes(prices={'600000.SH': 10}, positions=[
|
|
|
|
|
{'ts_code': '600000.SH', 'total_qty': 100, 'avg_cost': 8}])
|
|
|
|
|
self.funds(market_value=None, frozen_cash=None)
|
|
|
|
|
result = portfolio.overview()
|
|
|
|
|
self.assertIsNone(result['account_market_value'])
|
|
|
|
|
self.assertIsNone(result['frozen_cash'])
|
|
|
|
|
self.assertEqual(result['portfolio_mv'], 1000)
|
|
|
|
|
self.assertEqual(result['cash_avail'], 1806071.62)
|
|
|
|
|
|
|
|
|
|
|
2026-11-09 10:27:11 +08:00
|
|
|
class AccountPerformanceTest(unittest.TestCase):
|
|
|
|
|
def setUp(self):
|
|
|
|
|
self.fake = install_fakes(params={'PMS_TOTAL_SCALE': '2000000'})
|
|
|
|
|
enabled = patch.object(settings, 'INFRA_STRATEGY_BOOK_SCHEMA', True)
|
|
|
|
|
enabled.start(); self.addCleanup(enabled.stop)
|
|
|
|
|
self.capital = rotation_account.seed(10000, {'original': 5000, 'micro30': 0})
|
|
|
|
|
self.values = {'original': 5000, 'micro30': 0}
|
|
|
|
|
|
|
|
|
|
def read(self, **changes):
|
|
|
|
|
view = {'ready': True, 'cash_difference': 0, 'started_at': '2026-10-27T15:30:00',
|
|
|
|
|
'metrics': rotation_account.metrics(self.capital, self.values)}
|
|
|
|
|
view.update(changes)
|
|
|
|
|
with patch.object(rotation_accounting, 'view', return_value=view):
|
|
|
|
|
return portfolio.overview()['account_performance']
|
|
|
|
|
|
|
|
|
|
def test_both_books_realized_unrealized_and_booked_fees_are_included(self):
|
|
|
|
|
rotation_account.transfer(self.capital, 'original', 'micro30', 3000, self.values, 'move')
|
|
|
|
|
rotation_account.fill(self.capital, 'original', 'sell', 2000, 3, 'sell')
|
|
|
|
|
rotation_account.fill(self.capital, 'micro30', 'buy', 2500, 2, 'buy')
|
|
|
|
|
self.values = {'original': 3500, 'micro30': 2600}
|
|
|
|
|
result = self.read()
|
|
|
|
|
self.assertTrue(result['ready'])
|
|
|
|
|
self.assertEqual(result['profit'], 595)
|
2026-11-09 10:58:23 +08:00
|
|
|
self.assertAlmostEqual(result['profit_pct'], 595 / 15000)
|
2026-11-09 10:27:11 +08:00
|
|
|
self.assertEqual(result['started_at'], '2026-10-27T15:30:00')
|
|
|
|
|
|
|
|
|
|
def test_internal_transfer_and_user_scale_do_not_create_profit(self):
|
|
|
|
|
rotation_account.transfer(self.capital, 'original', 'micro30', 3000, self.values, 'move')
|
|
|
|
|
self.assertEqual(self.read()['profit'], 0)
|
2026-11-09 10:58:23 +08:00
|
|
|
self.assertEqual(self.read()['profit_pct'], 0)
|
2026-11-09 10:27:11 +08:00
|
|
|
|
|
|
|
|
def test_loss_keeps_sign(self):
|
|
|
|
|
self.values['original'] = 4321.12
|
|
|
|
|
self.assertEqual(self.read()['profit'], -678.88)
|
2026-11-09 10:58:23 +08:00
|
|
|
self.assertAlmostEqual(self.read()['profit_pct'], -678.88 / 15000)
|
|
|
|
|
|
|
|
|
|
def test_zero_or_unknown_capital_has_no_fabricated_rate(self):
|
|
|
|
|
for capital in (0, None):
|
|
|
|
|
result = self.read(metrics={'account': {'profit': 100},
|
|
|
|
|
'original': {'net_capital': capital}, 'micro30': {'net_capital': 0}})
|
|
|
|
|
self.assertEqual(result['profit'], 100)
|
|
|
|
|
self.assertIsNone(result['profit_pct'])
|
2026-11-09 10:27:11 +08:00
|
|
|
|
|
|
|
|
def test_missing_quotes_or_baseline_never_become_zero_profit(self):
|
|
|
|
|
for changes in ({'ready': False, 'reason': '估值待补'},
|
|
|
|
|
{'ready': False, 'reason': '分策略现金尚未初始化'},
|
|
|
|
|
{'metrics': {}}):
|
|
|
|
|
with self.subTest(changes=changes):
|
|
|
|
|
self.assertIsNone(self.read(**changes)['profit'])
|
|
|
|
|
|
|
|
|
|
def test_cash_disagreement_hides_unverified_account_profit(self):
|
|
|
|
|
result = self.read(cash_difference=100)
|
|
|
|
|
self.assertFalse(result['ready'])
|
|
|
|
|
self.assertIsNone(result['profit'])
|
|
|
|
|
|
|
|
|
|
def test_failure_does_not_hide_other_overview_fields(self):
|
|
|
|
|
with patch.object(rotation_accounting, 'view', side_effect=ValueError('test only')):
|
|
|
|
|
result = portfolio.overview()
|
|
|
|
|
self.assertTrue(result['ok'])
|
|
|
|
|
self.assertIsNone(result['account_performance']['profit'])
|
|
|
|
|
|
|
|
|
|
def test_nonfinite_profit_is_not_sent_to_page(self):
|
|
|
|
|
result = self.read(metrics={'account': {'profit': float('inf')}})
|
|
|
|
|
self.assertIsNone(result['profit'])
|
|
|
|
|
|
|
|
|
|
|
2026-11-09 10:58:23 +08:00
|
|
|
class HoldingPerformanceTest(unittest.TestCase):
|
|
|
|
|
def view(self, qty, cost, price):
|
|
|
|
|
install_fakes(positions=[{'ts_code': '600000.SH', 'total_qty': qty, 'avg_cost': cost}],
|
|
|
|
|
prices={'600000.SH': price} if price else {})
|
2026-11-10 12:06:38 +08:00
|
|
|
view = portfolio.positions_view()
|
|
|
|
|
view['_test_lots'] = [{'qty': qty, 'open_price': cost or 10, 'realized_pnl': 0 if cost else qty*10}]
|
|
|
|
|
return view
|
2026-11-09 10:58:23 +08:00
|
|
|
|
|
|
|
|
def combine(self, original, micro):
|
|
|
|
|
with patch.object(settings, 'INFRA_STRATEGY_BOOK_SCHEMA', True), \
|
2026-11-10 12:06:38 +08:00
|
|
|
patch.object(portfolio, 'positions_view', return_value=micro), \
|
|
|
|
|
patch.object(portfolio.pms_repo, 'list_lots', side_effect=lambda *a, **k: (original if books.CURRENT.get() == 'original' else micro)['_test_lots']):
|
2026-11-09 10:58:23 +08:00
|
|
|
return portfolio.holding_performance(portfolio.position_groups(original))
|
|
|
|
|
|
|
|
|
|
def test_two_books_same_stock_count_separately_and_rate_is_weighted(self):
|
|
|
|
|
result = self.combine(self.view(1000, 10, 11), self.view(500, 4, 3))
|
|
|
|
|
self.assertEqual(result['profit'], 500)
|
|
|
|
|
self.assertAlmostEqual(result['profit_pct'], 500 / 12000)
|
|
|
|
|
self.assertEqual([r['profit'] for r in result['strategies']], [1000, -500])
|
|
|
|
|
|
|
|
|
|
def test_missing_quote_hides_total_but_preserves_available_strategy(self):
|
|
|
|
|
result = self.combine(self.view(1000, 10, 11), self.view(500, 4, None))
|
|
|
|
|
self.assertFalse(result['ready'])
|
|
|
|
|
self.assertIsNone(result['profit'])
|
|
|
|
|
self.assertIsNone(result['profit_pct'])
|
|
|
|
|
self.assertEqual(result['strategies'][0]['profit'], 1000)
|
|
|
|
|
self.assertIsNone(result['strategies'][1]['profit'])
|
|
|
|
|
|
|
|
|
|
def test_empty_holdings_have_zero_amount_and_no_rate(self):
|
|
|
|
|
result = self.combine(self.view(0, 0, None), self.view(0, 0, None))
|
|
|
|
|
self.assertTrue(result['ready'])
|
|
|
|
|
self.assertEqual(result['profit'], 0)
|
|
|
|
|
self.assertIsNone(result['profit_pct'])
|
|
|
|
|
self.assertTrue(all(r['names_count'] == 0 for r in result['strategies']))
|
|
|
|
|
|
|
|
|
|
def test_recovered_cost_holding_still_has_profit_but_no_cost_rate(self):
|
|
|
|
|
result = self.combine(self.view(100, 0, 10), self.view(0, 0, None))
|
|
|
|
|
self.assertEqual(result['profit'], 1000)
|
|
|
|
|
self.assertIsNone(result['profit_pct'])
|
|
|
|
|
|
|
|
|
|
def test_strategy_read_failure_is_not_zero_profit(self):
|
|
|
|
|
original = self.view(100, 10, 11)
|
|
|
|
|
with patch.object(settings, 'INFRA_STRATEGY_BOOK_SCHEMA', True), \
|
2026-11-10 12:06:38 +08:00
|
|
|
patch.object(portfolio, 'positions_view', side_effect=ValueError('test only')), \
|
|
|
|
|
patch.object(portfolio.pms_repo, 'list_lots', return_value=original['_test_lots']):
|
2026-11-09 10:58:23 +08:00
|
|
|
result = portfolio.holding_performance(portfolio.position_groups(original))
|
|
|
|
|
self.assertFalse(result['ready'])
|
|
|
|
|
self.assertEqual(result['strategies'][0]['profit'], 100)
|
|
|
|
|
self.assertIsNone(result['strategies'][1]['profit'])
|
|
|
|
|
|
|
|
|
|
|
2026-10-26 16:24:14 +08:00
|
|
|
if __name__ == '__main__':
|
|
|
|
|
unittest.main()
|