tradingSystem/scripts/test_cost_precision.py

215 lines
12 KiB
Python
Raw Permalink Normal View History

"""成本三位精度贯穿成交、账本、页面数据和公示表;费用单列。"""
import unit_test_guard # noqa: F401
import io
import unittest
from pathlib import Path
from datetime import date
import openpyxl
from test_wiring import install_fakes
from app.core import ws_codec
from app.services import ledger_service, portfolio, publish_export
class CostPrecisionTests(unittest.TestCase):
def setUp(self):
self.fake = install_fakes(prices={'002979.SZ': 49.01},
params={'PMS_TOTAL_SCALE': '2000000'})
def book_trade(self, price, fee=0):
self.fake.insert_instruction(instruction_id='INS_PRECISION', origin_type='plan',
origin_id='P1', ts_code='002979.SZ', action='OPEN', side='buy', qty=100,
status='DISPATCHED')
self.fake.qmt.enqueue_order(instruction_id='INS_PRECISION_D01',
parent_id='INS_PRECISION', ts_code='002979.SZ', side='buy', qty=100,
limit_price=49.01, valid_until=0)
self.fake.qmt.put_trade(seq=1, instruction_id='INS_PRECISION_D01',
ts_code='002979.SZ', side='buy', qty=100, price=price, fee=fee)
result = ledger_service.consume_ws_trades()
self.assertEqual((result['trades'], result['actions']), (1, 1))
def test_three_decimal_trade_reaches_book_page_and_xlsx_unchanged(self):
self.book_trade(48.296)
self.assertEqual(self.fake.lots[0]['open_price'], 48.296)
self.assertEqual(self.fake.positions['002979.SZ']['avg_cost'], 48.296)
self.assertEqual(portfolio.positions_view()['held'][0]['avg_cost'], 48.296)
snapshot = publish_export.compute_snapshot()
self.assertAlmostEqual(snapshot['holdings'][0]['cost'], 48.296)
self.assertEqual(snapshot['holdings'][0]['amount'], 4829.60)
workbook = openpyxl.load_workbook(io.BytesIO(
publish_export.build_workbook(snapshot, publish_export._nav_series(snapshot))))
sheet = workbook['Sheet1']
self.assertAlmostEqual(sheet['K5'].value, 48.296)
self.assertEqual(sheet['K5'].number_format, '0.000')
self.assertEqual(sheet['M5'].number_format, '0.000')
self.assertEqual(sheet['G5'].number_format, '#,##0.00')
self.assertEqual(sheet['S5'].number_format, '#,##0.00')
self.assertTrue(any('未回报费用不视为零' in str(cell.value or '')
for row in sheet for cell in row))
def test_fee_cost_is_not_invented_by_padding_trade_price(self):
# 券商可能含费成本48.296,但48.29成交+0.60费用在PMS必须分别记账。
self.book_trade(48.29, fee=.60)
self.assertEqual(self.fake.positions['002979.SZ']['avg_cost'], 48.29)
self.assertEqual(self.fake.cash_flows[0]['amount'], -.60)
snapshot = publish_export.compute_snapshot()
self.assertEqual(snapshot['holdings'][0]['cost'], 48.29)
self.assertEqual(snapshot['holdings'][0]['amount'], 4829.00)
self.assertEqual(snapshot['fee_resid'], .60)
def closed_profit_fixture(self):
self.fake.insert_lot(ts_code='002979.SZ', lot_type='BASE', qty=1000,
open_price=10, open_date=date.today())
self.fake.close_lot_qty(self.fake.lots[-1]['id'], qty=1000,
close_price=11, realized_pnl=1000)
return int(date.today().strftime('%Y%m%d'))
def test_negative_fee_cash_flow_reduces_closed_profit(self):
day = self.closed_profit_fixture()
self.fake.insert_cash_flow(ymd=day, kind='FEE', amount=-12.5, ts_code='002979.SZ')
self.fake.insert_cash_flow(ymd=day, kind='CALIBRATE', amount=-3.5)
snapshot = publish_export.compute_snapshot()
self.assertEqual(snapshot['closed'][0]['pnl'], 987.5)
self.assertEqual(snapshot['realized'], 987.5)
self.assertEqual(snapshot['fee_resid'], 3.5)
self.assertEqual([r['amount'] for r in self.fake.cash_flows], [-12.5, -3.5])
def test_positive_fee_refund_offsets_cost_instead_of_becoming_another_fee(self):
day = self.closed_profit_fixture()
self.fake.insert_cash_flow(ymd=day, kind='FEE', amount=-12.5, ts_code='002979.SZ')
self.fake.insert_cash_flow(ymd=day, kind='FEE', amount=2.5, ts_code='002979.SZ')
snapshot = publish_export.compute_snapshot()
self.assertEqual(snapshot['closed'][0]['pnl'], 990)
self.assertEqual(snapshot['fee_resid'], 0)
self.assertEqual([r['amount'] for r in self.fake.cash_flows], [-12.5, 2.5])
def test_unallocated_refund_keeps_negative_cost_and_is_labelled_as_refund(self):
day = int(date.today().strftime('%Y%m%d'))
self.fake.insert_cash_flow(ymd=day, kind='CALIBRATE', amount=2.5)
snapshot = publish_export.compute_snapshot()
self.assertEqual(snapshot['fee_resid'], -2.5)
workbook = openpyxl.load_workbook(io.BytesIO(
publish_export.build_workbook(snapshot, publish_export._nav_series(snapshot))))
self.assertTrue(any('2.50 元费用返还' in str(cell.value or '')
for row in workbook['Sheet1'] for cell in row))
def test_qmt_position_snapshot_keeps_cost_third_decimal(self):
value = ws_codec.parse_positions_snapshot({'items': [
{'ts_code': '002979.SZ', 'total_qty': 100, 'avail_qty': 100,
'cost_price': '48.296', 'market_price': '49.01'}]})
self.assertEqual(value['rows'][0]['cost'], 48.296)
def test_weighted_average_is_displayed_to_three_places_without_losing_money(self):
for qty, price in ((100, 48.290), (200, 48.291)):
self.fake.insert_lot(ts_code='002979.SZ', lot_type='BASE', qty=qty,
open_price=price, open_date=date.today())
snapshot = publish_export.compute_snapshot()
row = snapshot['holdings'][0]
self.assertEqual(row['amount'], 14487.20)
self.assertAlmostEqual(row['cost'], 48.29066666666667)
self.assertEqual(snapshot['hold_pnl'], 215.80)
workbook = openpyxl.load_workbook(io.BytesIO(
publish_export.build_workbook(snapshot, publish_export._nav_series(snapshot))))
sheet = workbook['Sheet1']
self.assertAlmostEqual(sheet['K5'].value * sheet['L5'].value, 14487.20)
self.assertEqual(sheet['K5'].number_format, '0.000')
# 表格可编辑:成本、股数变化同时进入成本金额与盈亏,再进入小计和净值。
self.assertEqual(sheet['G5'].value, '=ROUND(K5*L5,2)')
self.assertEqual(sheet['Q5'].value, '=M5-K5')
self.assertEqual(sheet['S5'].value, '=ROUND(ROUND(M5*L5,2)-G5,2)')
self.assertEqual(sheet['G6'].value, '=SUM(G5:G5)')
self.assertEqual(sheet['S6'].value, '=SUM(S5:S5)')
def test_closed_average_keeps_amount_precision(self):
for qty, price, close_price in ((100, 48.290, 49.010), (200, 48.291, 49.011)):
self.fake.insert_lot(ts_code='002979.SZ', lot_type='BASE', qty=qty,
open_price=price, open_date=date.today())
self.fake.close_lot_qty(self.fake.lots[-1]['id'], qty=qty,
close_price=close_price, realized_pnl=qty*(close_price-price))
snapshot = publish_export.compute_snapshot()
row = snapshot['closed'][0]
self.assertEqual(row['amount'], 14487.20)
self.assertAlmostEqual(row['cost'] * row['qty'], 14487.20)
self.assertAlmostEqual(row['settle'] * row['qty'], 14703.20)
self.assertEqual(row['pnl'], 216.00)
def test_odd_lot_cost_and_settlement_do_not_inherit_cent_rounding(self):
self.fake.insert_lot(ts_code='002979.SZ', lot_type='BASE', qty=2,
open_price=48.296, open_date=date.today())
self.fake.close_lot_qty(self.fake.lots[-1]['id'], qty=1,
close_price=49.011, realized_pnl=.715)
snapshot = publish_export.compute_snapshot()
for row in (snapshot['holdings'][0], snapshot['closed'][0]):
self.assertEqual(row['qty'], 1)
self.assertEqual(row['amount'], 48.30)
self.assertEqual(row['cost'], 48.296)
self.assertEqual(snapshot['closed'][0]['settle'], 49.011)
self.assertEqual(snapshot['hold_pnl'], .71)
workbook = openpyxl.load_workbook(io.BytesIO(
publish_export.build_workbook(snapshot, publish_export._nav_series(snapshot))))
sheet = workbook['Sheet1']
self.assertEqual(sheet['K5'].value, 48.296)
self.assertEqual(sheet['K8'].value, 48.296)
self.assertEqual(sheet['M8'].value, 49.011)
def test_half_cent_cost_matches_workbook_round_without_rounding_unit_cost(self):
self.fake.insert_lot(ts_code='002979.SZ', lot_type='BASE', qty=1,
open_price=48.285, open_date=date.today())
snapshot = publish_export.compute_snapshot()
self.assertEqual(snapshot['holdings'][0]['cost'], 48.285)
self.assertEqual(snapshot['holdings'][0]['amount'], 48.29)
self.assertEqual(snapshot['hold_cost'], 48.29)
self.assertEqual(snapshot['hold_pnl'], .72)
self.assertEqual(snapshot['open_room'], 1999951.71)
workbook = openpyxl.load_workbook(io.BytesIO(
publish_export.build_workbook(snapshot, publish_export._nav_series(snapshot))))
sheet = workbook['Sheet1']
self.assertEqual(sheet['K5'].value, 48.285)
self.assertEqual(sheet['G5'].value, '=ROUND(K5*L5,2)')
self.assertEqual(sheet['S5'].value, '=ROUND(ROUND(M5*L5,2)-G5,2)')
def test_multiple_lots_accumulate_before_half_cent_rounding(self):
for price in (48.281, 48.284):
self.fake.insert_lot(ts_code='002979.SZ', lot_type='BASE', qty=1,
open_price=price, open_date=date.today())
snapshot = publish_export.compute_snapshot()
row = snapshot['holdings'][0]
self.assertEqual((row['qty'], row['cost'], row['amount']), (2, 48.2825, 96.57))
self.assertEqual(snapshot['hold_pnl'], 1.45)
def test_market_value_rounds_to_cents_before_profit_subtraction(self):
for cost, price, expected in ((48.29, 49.015, .73), (49.01, 48.285, -.72)):
with self.subTest(cost=cost, price=price):
self.fake = install_fakes(prices={'002979.SZ': price},
params={'PMS_TOTAL_SCALE': '2000000'})
self.fake.insert_lot(ts_code='002979.SZ', lot_type='BASE', qty=1,
open_price=cost, open_date=date.today())
snapshot = publish_export.compute_snapshot()
self.assertEqual(snapshot['hold_pnl'], expected)
self.assertIsInstance(snapshot['hold_pnl'], float)
def test_missing_quote_uses_exact_cost_without_false_profit(self):
for lots in (((100, 48.290), (200, 48.291)), ((1, 48.285),)):
with self.subTest(lots=lots):
self.fake = install_fakes(prices={}, params={'PMS_TOTAL_SCALE': '2000000'})
for qty, price in lots:
self.fake.insert_lot(ts_code='002979.SZ', lot_type='BASE', qty=qty,
open_price=price, open_date=date.today())
snapshot = publish_export.compute_snapshot()
self.assertEqual(snapshot['price_missing'], ['002979.SZ'])
self.assertEqual(snapshot['hold_pnl'], 0)
def test_price_formatting_is_separate_from_amount_and_quote_fields(self):
page = (Path(__file__).resolve().parents[1] / 'app/web/static/index.html').read_text()
self.assertIn("? '—' : Number(v).toFixed(3)", page)
for field in ('avg_cost', 'open_price', 'close_avg_price'):
self.assertIn('costPrice(s.row.' + field + ')', page)
self.assertNotIn('costPrice(s.row.market_value)', page)
self.assertNotIn('costPrice(s.row.limit_price)', page)
self.assertIn('不是券商含费成本', page)
self.assertIn('成交均价,不含手续费。', page)
if __name__ == '__main__':
unittest.main()