141 lines
7.6 KiB
Python
141 lines
7.6 KiB
Python
"""成本三位精度贯穿成交、账本、页面数据和公示表;费用单列。"""
|
||
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(abs(snapshot['fee_resid']), .60)
|
||
|
||
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(M5*L5-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_missing_quote_uses_exact_cost_without_false_profit(self):
|
||
self.fake = install_fakes(prices={}, params={'PMS_TOTAL_SCALE': '2000000'})
|
||
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()
|
||
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()
|