改进模拟账户量化导出表
This commit is contained in:
parent
8d3f87d5b0
commit
13028a18af
|
|
@ -276,7 +276,7 @@ def _nav_series(snapshot: dict) -> list:
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- 版式 (模板填充)
|
# ---------------------------------------------------------------- 版式 (模板填充)
|
||||||
def _copy_row_style(ws, src_row: int, dst_row: int, cols=range(2, 22)):
|
def _copy_row_style(ws, src_row: int, dst_row: int, cols=range(2, 23)):
|
||||||
"""只拷单元格样式。行高不在这拷 —— openpyxl 插行不搬 row_dimensions, 拷邻行行高
|
"""只拷单元格样式。行高不在这拷 —— openpyxl 插行不搬 row_dimensions, 拷邻行行高
|
||||||
等于拷一个错位的旧值, 行高在 build_workbook 里按最终行位统一重排。"""
|
等于拷一个错位的旧值, 行高在 build_workbook 里按最终行位统一重排。"""
|
||||||
for col in cols:
|
for col in cols:
|
||||||
|
|
@ -292,41 +292,43 @@ def _put(ws, row, col, value, fmt=None):
|
||||||
|
|
||||||
|
|
||||||
def _entry_row(ws, row, seq, e, *, date2, px):
|
def _entry_row(ws, row, seq, e, *, date2, px):
|
||||||
vals = [seq, e["account"], e["code"], e["name"], e["amount"], e["open_date"],
|
vals = [seq, e["account"], e["code"], e["name"], e["amount"], None, e["open_date"],
|
||||||
date2, e["structure"], e["cost"], e["qty"], px, e["days"],
|
date2, e["structure"], e["cost"], e["qty"], px, e["days"],
|
||||||
_FIN_NONE, _FIN_NONE,
|
_FIN_NONE, _FIN_NONE,
|
||||||
f"=M{row}-K{row}", # Q 每股较期初价盈
|
f"=N{row}-L{row}",
|
||||||
f"=IF(K{row}=0,0,Q{row}/K{row})"] # R 较期初价涨跌幅
|
f"=IF(L{row}=0,0,R{row}/L{row})"]
|
||||||
for i, v in enumerate(vals):
|
for i, v in enumerate(vals):
|
||||||
_put(ws, row, 3 + i, v)
|
_put(ws, row, 3 + i, v)
|
||||||
# 均价统一显示三位、金额两位;格式不能反过来截断原始数值。
|
# 均价统一显示三位、金额两位;格式不能反过来截断原始数值。
|
||||||
for col in (11, 13, 17):
|
for col in (12, 14, 18):
|
||||||
ws.cell(row=row, column=col).number_format = "0.000"
|
ws.cell(row=row, column=col).number_format = "0.000"
|
||||||
for col in (7, 19):
|
for col in (7, 8, 20):
|
||||||
ws.cell(row=row, column=col).number_format = "#,##0.00"
|
ws.cell(row=row, column=col).number_format = "#,##0.00"
|
||||||
# 表格里手动修订成本或股数后,成本金额和持仓盈亏必须一起重算。
|
# 表格里手动修订成本或股数后,成本金额和持仓盈亏必须一起重算。
|
||||||
_put(ws, row, 7, f"=ROUND(K{row}*L{row},2)")
|
_put(ws, row, 7, f"=ROUND(L{row}*M{row},2)")
|
||||||
# S 总持股浮动盈亏: 持仓 = 市值减成本金额;平仓 = 含费实得,沿用账本数值
|
|
||||||
if e.get("pnl") is None:
|
if e.get("pnl") is None:
|
||||||
_put(ws, row, 19, f"=ROUND(ROUND(M{row}*L{row},2)-G{row},2)")
|
_put(ws, row, 8, f"=ROUND(N{row}*M{row},2)")
|
||||||
|
_put(ws, row, 20, f"=ROUND(H{row}-G{row},2)")
|
||||||
else:
|
else:
|
||||||
_put(ws, row, 19, e["pnl"])
|
_put(ws, row, 20, e["pnl"])
|
||||||
_put(ws, row, 20, f"=IF(G{row}=0,0,S{row}/G{row})") # T 持有收益率
|
_put(ws, row, 21, f"=IF(G{row}=0,0,T{row}/G{row})")
|
||||||
_put(ws, row, 21, f"=1+T{row}") # U 净值估算
|
_put(ws, row, 22, f"=1+U{row}")
|
||||||
|
|
||||||
|
|
||||||
def _subtotal(ws, row, top, bottom, has_rows):
|
def _subtotal(ws, row, top, bottom, has_rows):
|
||||||
_put(ws, row, 7, f"=SUM(G{top}:G{bottom})" if has_rows else 0)
|
_put(ws, row, 7, f"=SUM(G{top}:G{bottom})" if has_rows else 0)
|
||||||
_put(ws, row, 19, f"=SUM(S{top}:S{bottom})" if has_rows else 0)
|
_put(ws, row, 20, f"=SUM(T{top}:T{bottom})" if has_rows else 0)
|
||||||
_put(ws, row, 20, f"=IF(G{row}=0,0,S{row}/G{row})")
|
_put(ws, row, 21, f"=IF(G{row}=0,0,T{row}/G{row})")
|
||||||
_put(ws, row, 21, f"=1+T{row}")
|
_put(ws, row, 22, f"=1+U{row}")
|
||||||
|
|
||||||
|
|
||||||
def build_workbook(s: dict, nav_rows: list) -> bytes:
|
def build_workbook(s: dict, nav_rows: list) -> bytes:
|
||||||
"""把快照填进公司模板。纯函数 (不碰库), 可离线测试。"""
|
"""把快照填进公司模板。纯函数 (不碰库), 可离线测试。"""
|
||||||
import openpyxl
|
import openpyxl
|
||||||
from openpyxl.chart import LineChart, Reference
|
from openpyxl.chart import LineChart, Reference
|
||||||
|
from openpyxl.chart.label import DataLabelList
|
||||||
from openpyxl.chart.marker import Marker
|
from openpyxl.chart.marker import Marker
|
||||||
|
from openpyxl.drawing.spreadsheet_drawing import AnchorMarker, TwoCellAnchor
|
||||||
from openpyxl.formatting.formatting import ConditionalFormattingList
|
from openpyxl.formatting.formatting import ConditionalFormattingList
|
||||||
from openpyxl.formatting.rule import CellIsRule
|
from openpyxl.formatting.rule import CellIsRule
|
||||||
from openpyxl.styles import Font, PatternFill
|
from openpyxl.styles import Font, PatternFill
|
||||||
|
|
@ -351,6 +353,15 @@ def build_workbook(s: dict, nav_rows: list) -> bytes:
|
||||||
# openpyxl 的插行不搬合并区 —— 先全拆, 插完行按最终行位重新合并
|
# openpyxl 的插行不搬合并区 —— 先全拆, 插完行按最终行位重新合并
|
||||||
for rng in list(ws.merged_cells.ranges):
|
for rng in list(ws.merged_cells.ranges):
|
||||||
ws.unmerge_cells(str(rng))
|
ws.unmerge_cells(str(rng))
|
||||||
|
ws.insert_cols(8)
|
||||||
|
for key, dim in reversed(list(ws.column_dimensions.items())):
|
||||||
|
if dim.min >= 8:
|
||||||
|
del ws.column_dimensions[key]
|
||||||
|
dim.min += 1
|
||||||
|
dim.max += 1
|
||||||
|
dim.index = get_column_letter(dim.min)
|
||||||
|
ws.column_dimensions[dim.index] = dim
|
||||||
|
ws.column_dimensions['H'].width = ws.column_dimensions['G'].width
|
||||||
if n_c > 1: # 自底向上插, 行号才不互相踩
|
if n_c > 1: # 自底向上插, 行号才不互相踩
|
||||||
ws.insert_rows(_R_CPROTO + 1, n_c - 1)
|
ws.insert_rows(_R_CPROTO + 1, n_c - 1)
|
||||||
if n_h > 1:
|
if n_h > 1:
|
||||||
|
|
@ -371,8 +382,12 @@ def build_workbook(s: dict, nav_rows: list) -> bytes:
|
||||||
# ---- 标题与时间 ----
|
# ---- 标题与时间 ----
|
||||||
_put(ws, 1, 2, s["title"])
|
_put(ws, 1, 2, s["title"])
|
||||||
start = nav_rows[0]["ymd"] if nav_rows else int(s["today"].strftime("%Y%m%d"))
|
start = nav_rows[0]["ymd"] if nav_rows else int(s["today"].strftime("%Y%m%d"))
|
||||||
_put(ws, 2, 20, datetime.strptime(str(start), "%Y%m%d").date())
|
_put(ws, 2, 21, datetime.strptime(str(start), "%Y%m%d").date())
|
||||||
_put(ws, 3, 20, s["today"])
|
_put(ws, 3, 21, s["today"])
|
||||||
|
for row in (4, chead, *range(hold_top, hsub + 1), *range(close_top, csub + 1), sum1):
|
||||||
|
ws.cell(row, 8)._style = copy(ws.cell(row, 7)._style)
|
||||||
|
for row in (4, chead):
|
||||||
|
_put(ws, row, 8, "市值(元)")
|
||||||
|
|
||||||
# ---- 明细与小计 ----
|
# ---- 明细与小计 ----
|
||||||
if s["holdings"]:
|
if s["holdings"]:
|
||||||
|
|
@ -381,6 +396,7 @@ def build_workbook(s: dict, nav_rows: list) -> bytes:
|
||||||
else:
|
else:
|
||||||
_put(ws, hold_top, 6, "(当前无持仓)")
|
_put(ws, hold_top, 6, "(当前无持仓)")
|
||||||
_subtotal(ws, hsub, hold_top, hsub - 1, bool(s["holdings"]))
|
_subtotal(ws, hsub, hold_top, hsub - 1, bool(s["holdings"]))
|
||||||
|
_put(ws, hsub, 8, f"=SUM(H{hold_top}:H{hsub - 1})", fmt="#,##0.00")
|
||||||
if s["closed"]:
|
if s["closed"]:
|
||||||
for i, e in enumerate(s["closed"]):
|
for i, e in enumerate(s["closed"]):
|
||||||
_entry_row(ws, close_top + i, i + 1, e, date2=e["close_date"], px=e["settle"])
|
_entry_row(ws, close_top + i, i + 1, e, date2=e["close_date"], px=e["settle"])
|
||||||
|
|
@ -390,20 +406,21 @@ def build_workbook(s: dict, nav_rows: list) -> bytes:
|
||||||
|
|
||||||
# ---- 汇总两行 (公式引用两张小计, 口径同模板) ----
|
# ---- 汇总两行 (公式引用两张小计, 口径同模板) ----
|
||||||
_put(ws, sum1, 7, f"=G{hsub}")
|
_put(ws, sum1, 7, f"=G{hsub}")
|
||||||
_put(ws, sum1, 19, f"=S{hsub}+S{csub}")
|
_put(ws, sum1, 8, f"=H{hsub}", fmt="#,##0.00")
|
||||||
_put(ws, sum1, 20, f"=S{sum1}/{s['scale']}")
|
_put(ws, sum1, 20, f"=T{hsub}+T{csub}")
|
||||||
_put(ws, sum1, 21, f"=1+T{sum1}")
|
_put(ws, sum1, 21, f"=T{sum1}/{s['scale']}")
|
||||||
_put(ws, sum2, 6, f"={s['scale']}+S{csub}")
|
_put(ws, sum1, 22, f"=1+U{sum1}")
|
||||||
_put(ws, sum2, 10, f"=F{sum2}-G{sum1}")
|
_put(ws, sum2, 6, f"={s['scale']}+T{csub}")
|
||||||
_put(ws, sum2, 12, f"=IF(F{sum2}=0,0,G{sum1}/F{sum2})")
|
_put(ws, sum2, 11, f"=F{sum2}-G{sum1}")
|
||||||
_put(ws, sum2, 15, f"=U{sum1}")
|
_put(ws, sum2, 13, f"=IF(F{sum2}=0,0,G{sum1}/F{sum2})")
|
||||||
_put(ws, sum2, 17, f"=U{sum1}")
|
_put(ws, sum2, 16, f"=V{sum1}")
|
||||||
|
_put(ws, sum2, 18, f"=V{sum1}")
|
||||||
|
|
||||||
# ---- 合并区按最终行位重排 (与模板同构) ----
|
# ---- 合并区按最终行位重排 (与模板同构) ----
|
||||||
for rng in ([f"B1:T1", f"B4:B{hsub}", f"B{chead}:B{csub}",
|
for rng in (["B1:V1", f"B4:B{hsub}", f"B{chead}:B{csub}",
|
||||||
f"B{sum1}:F{sum1}", f"H{sum1}:I{sum1}", f"Q{sum1}:R{sum1}",
|
f"B{sum1}:F{sum1}", f"I{sum1}:J{sum1}", f"R{sum1}:S{sum1}",
|
||||||
f"B{sum2}:E{sum2}", f"F{sum2}:G{sum2}", f"H{sum2}:I{sum2}",
|
f"B{sum2}:E{sum2}", f"F{sum2}:H{sum2}", f"I{sum2}:J{sum2}",
|
||||||
f"M{sum2}:N{sum2}", f"R{sum2}:T{sum2}"]):
|
f"N{sum2}:O{sum2}", f"S{sum2}:U{sum2}"]):
|
||||||
ws.merge_cells(rng)
|
ws.merge_cells(rng)
|
||||||
|
|
||||||
# ---- 行高按最终行位重排 (openpyxl 插行不搬行高, 与合并区同病同治) ----
|
# ---- 行高按最终行位重排 (openpyxl 插行不搬行高, 与合并区同病同治) ----
|
||||||
|
|
@ -415,21 +432,20 @@ def build_workbook(s: dict, nav_rows: list) -> bytes:
|
||||||
rd.height = h0
|
rd.height = h0
|
||||||
rd.hidden = False
|
rd.hidden = False
|
||||||
|
|
||||||
# ---- 红涨绿跌条件格式 (原表样式按最终行位重建: Q/R/S 红涨绿跌字色,
|
# ---- 红涨绿跌条件格式按最终行列重建。 ----
|
||||||
# 持仓 S 列独一份用红绿底色, 0 也算红; 颜色与原表 dxf 逐字节同) ----
|
|
||||||
def _font_rule(op, color):
|
def _font_rule(op, color):
|
||||||
return CellIsRule(operator=op, formula=["0"], font=Font(color=color))
|
return CellIsRule(operator=op, formula=["0"], font=Font(color=color))
|
||||||
|
|
||||||
for rng in (f"Q{hold_top}:R{hsub - 1}", f"Q{close_top}:S{csub - 1}",
|
for rng in (f"R{hold_top}:S{hsub - 1}", f"R{close_top}:T{csub - 1}",
|
||||||
f"S{hsub} S{csub}"):
|
f"T{hsub} T{csub}"):
|
||||||
ws.conditional_formatting.add(rng, _font_rule("greaterThan", "FFFF0000"))
|
ws.conditional_formatting.add(rng, _font_rule("greaterThan", "FFFF0000"))
|
||||||
ws.conditional_formatting.add(rng, _font_rule("lessThan", "FF00B050"))
|
ws.conditional_formatting.add(rng, _font_rule("lessThan", "FF00B050"))
|
||||||
ws.conditional_formatting.add(
|
ws.conditional_formatting.add(
|
||||||
f"S{hold_top}:S{hsub - 1}",
|
f"T{hold_top}:T{hsub - 1}",
|
||||||
CellIsRule(operator="lessThan", formula=["0"],
|
CellIsRule(operator="lessThan", formula=["0"],
|
||||||
fill=PatternFill(fill_type="solid", bgColor="FF00B050")))
|
fill=PatternFill(fill_type="solid", bgColor="FF00B050")))
|
||||||
ws.conditional_formatting.add(
|
ws.conditional_formatting.add(
|
||||||
f"S{hold_top}:S{hsub - 1}",
|
f"T{hold_top}:T{hsub - 1}",
|
||||||
CellIsRule(operator="greaterThanOrEqual", formula=["0"],
|
CellIsRule(operator="greaterThanOrEqual", formula=["0"],
|
||||||
fill=PatternFill(fill_type="solid", bgColor="FFFF0000")))
|
fill=PatternFill(fill_type="solid", bgColor="FFFF0000")))
|
||||||
|
|
||||||
|
|
@ -451,7 +467,7 @@ def build_workbook(s: dict, nav_rows: list) -> bytes:
|
||||||
# ---- 净值序列 + 折线图 (双系列同原表: 净值主轴 + 仓位占比副轴, 标题同原图;
|
# ---- 净值序列 + 折线图 (双系列同原表: 净值主轴 + 仓位占比副轴, 标题同原图;
|
||||||
# 每个数据点带标记, 首日只有一个点也看得见; plotVisOnly=0 隐藏单元格照画) ----
|
# 每个数据点带标记, 首日只有一个点也看得见; plotVisOnly=0 隐藏单元格照画) ----
|
||||||
base = note_row + 1
|
base = note_row + 1
|
||||||
NC = 25 # Y 列起三列数据, 在图区右侧, 不碰表体
|
NC = 26
|
||||||
hd = Font(name="宋体", size=10, bold=True)
|
hd = Font(name="宋体", size=10, bold=True)
|
||||||
for j, h in enumerate(["时间", "净值数据", "仓位占比"]):
|
for j, h in enumerate(["时间", "净值数据", "仓位占比"]):
|
||||||
_put(ws, base, NC + j, h).font = hd
|
_put(ws, base, NC + j, h).font = hd
|
||||||
|
|
@ -466,11 +482,13 @@ def build_workbook(s: dict, nav_rows: list) -> bytes:
|
||||||
cats = Reference(ws, min_col=NC, min_row=base + 1, max_row=last)
|
cats = Reference(ws, min_col=NC, min_row=base + 1, max_row=last)
|
||||||
nav_c = LineChart()
|
nav_c = LineChart()
|
||||||
nav_c.title = "量化净值数据及持仓仓位变化"
|
nav_c.title = "量化净值数据及持仓仓位变化"
|
||||||
nav_c.height, nav_c.width = 9.0, 30.0 # 与模板图区 (B..U 宽 × 16 行) 相当
|
|
||||||
nav_c.add_data(Reference(ws, min_col=NC + 1, min_row=base, max_row=last),
|
nav_c.add_data(Reference(ws, min_col=NC + 1, min_row=base, max_row=last),
|
||||||
titles_from_data=True)
|
titles_from_data=True)
|
||||||
nav_c.set_categories(cats)
|
nav_c.set_categories(cats)
|
||||||
nav_c.y_axis.number_format = "0.000"
|
nav_c.y_axis.number_format = "0.000"
|
||||||
|
nav_c.series[0].dLbls = DataLabelList(showVal=True, numFmt="0.0000", dLblPos="t",
|
||||||
|
showCatName=False, showSerName=False, showLegendKey=False,
|
||||||
|
showPercent=False, showBubbleSize=False)
|
||||||
pos_c = LineChart()
|
pos_c = LineChart()
|
||||||
pos_c.add_data(Reference(ws, min_col=NC + 2, min_row=base, max_row=last),
|
pos_c.add_data(Reference(ws, min_col=NC + 2, min_row=base, max_row=last),
|
||||||
titles_from_data=True)
|
titles_from_data=True)
|
||||||
|
|
@ -485,8 +503,10 @@ def build_workbook(s: dict, nav_rows: list) -> bytes:
|
||||||
ser.marker = Marker(symbol=sym, size=7)
|
ser.marker = Marker(symbol=sym, size=7)
|
||||||
nav_c += pos_c
|
nav_c += pos_c
|
||||||
nav_c.visible_cells_only = False
|
nav_c.visible_cells_only = False
|
||||||
ws.add_chart(nav_c, f"B{base}")
|
nav_c.anchor = TwoCellAnchor(_from=AnchorMarker(col=1, row=base - 1),
|
||||||
for col, w in {25: 11, 26: 10, 27: 10}.items():
|
to=AnchorMarker(col=22, row=base + 16))
|
||||||
|
ws.add_chart(nav_c)
|
||||||
|
for col, w in {NC: 11, NC + 1: 10, NC + 2: 10}.items():
|
||||||
ws.column_dimensions[get_column_letter(col)].width = w
|
ws.column_dimensions[get_column_letter(col)].width = w
|
||||||
|
|
||||||
buf = io.BytesIO()
|
buf = io.BytesIO()
|
||||||
|
|
|
||||||
|
|
@ -39,11 +39,11 @@ class CostPrecisionTests(unittest.TestCase):
|
||||||
workbook = openpyxl.load_workbook(io.BytesIO(
|
workbook = openpyxl.load_workbook(io.BytesIO(
|
||||||
publish_export.build_workbook(snapshot, publish_export._nav_series(snapshot))))
|
publish_export.build_workbook(snapshot, publish_export._nav_series(snapshot))))
|
||||||
sheet = workbook['Sheet1']
|
sheet = workbook['Sheet1']
|
||||||
self.assertAlmostEqual(sheet['K5'].value, 48.296)
|
self.assertAlmostEqual(sheet['L5'].value, 48.296)
|
||||||
self.assertEqual(sheet['K5'].number_format, '0.000')
|
self.assertEqual(sheet['L5'].number_format, '0.000')
|
||||||
self.assertEqual(sheet['M5'].number_format, '0.000')
|
self.assertEqual(sheet['N5'].number_format, '0.000')
|
||||||
self.assertEqual(sheet['G5'].number_format, '#,##0.00')
|
self.assertEqual(sheet['G5'].number_format, '#,##0.00')
|
||||||
self.assertEqual(sheet['S5'].number_format, '#,##0.00')
|
self.assertEqual(sheet['T5'].number_format, '#,##0.00')
|
||||||
self.assertTrue(any('未回报费用不视为零' in str(cell.value or '')
|
self.assertTrue(any('未回报费用不视为零' in str(cell.value or '')
|
||||||
for row in sheet for cell in row))
|
for row in sheet for cell in row))
|
||||||
|
|
||||||
|
|
@ -111,14 +111,14 @@ class CostPrecisionTests(unittest.TestCase):
|
||||||
workbook = openpyxl.load_workbook(io.BytesIO(
|
workbook = openpyxl.load_workbook(io.BytesIO(
|
||||||
publish_export.build_workbook(snapshot, publish_export._nav_series(snapshot))))
|
publish_export.build_workbook(snapshot, publish_export._nav_series(snapshot))))
|
||||||
sheet = workbook['Sheet1']
|
sheet = workbook['Sheet1']
|
||||||
self.assertAlmostEqual(sheet['K5'].value * sheet['L5'].value, 14487.20)
|
self.assertAlmostEqual(sheet['L5'].value * sheet['M5'].value, 14487.20)
|
||||||
self.assertEqual(sheet['K5'].number_format, '0.000')
|
self.assertEqual(sheet['L5'].number_format, '0.000')
|
||||||
# 表格可编辑:成本、股数变化同时进入成本金额与盈亏,再进入小计和净值。
|
# 表格可编辑:成本、股数变化同时进入成本金额与盈亏,再进入小计和净值。
|
||||||
self.assertEqual(sheet['G5'].value, '=ROUND(K5*L5,2)')
|
self.assertEqual(sheet['G5'].value, '=ROUND(L5*M5,2)')
|
||||||
self.assertEqual(sheet['Q5'].value, '=M5-K5')
|
self.assertEqual(sheet['R5'].value, '=N5-L5')
|
||||||
self.assertEqual(sheet['S5'].value, '=ROUND(ROUND(M5*L5,2)-G5,2)')
|
self.assertEqual(sheet['T5'].value, '=ROUND(H5-G5,2)')
|
||||||
self.assertEqual(sheet['G6'].value, '=SUM(G5:G5)')
|
self.assertEqual(sheet['G6'].value, '=SUM(G5:G5)')
|
||||||
self.assertEqual(sheet['S6'].value, '=SUM(S5:S5)')
|
self.assertEqual(sheet['T6'].value, '=SUM(T5:T5)')
|
||||||
|
|
||||||
def test_closed_average_keeps_amount_precision(self):
|
def test_closed_average_keeps_amount_precision(self):
|
||||||
for qty, price, close_price in ((100, 48.290, 49.010), (200, 48.291, 49.011)):
|
for qty, price, close_price in ((100, 48.290, 49.010), (200, 48.291, 49.011)):
|
||||||
|
|
@ -148,9 +148,9 @@ class CostPrecisionTests(unittest.TestCase):
|
||||||
workbook = openpyxl.load_workbook(io.BytesIO(
|
workbook = openpyxl.load_workbook(io.BytesIO(
|
||||||
publish_export.build_workbook(snapshot, publish_export._nav_series(snapshot))))
|
publish_export.build_workbook(snapshot, publish_export._nav_series(snapshot))))
|
||||||
sheet = workbook['Sheet1']
|
sheet = workbook['Sheet1']
|
||||||
self.assertEqual(sheet['K5'].value, 48.296)
|
self.assertEqual(sheet['L5'].value, 48.296)
|
||||||
self.assertEqual(sheet['K8'].value, 48.296)
|
self.assertEqual(sheet['L8'].value, 48.296)
|
||||||
self.assertEqual(sheet['M8'].value, 49.011)
|
self.assertEqual(sheet['N8'].value, 49.011)
|
||||||
|
|
||||||
def test_half_cent_cost_matches_workbook_round_without_rounding_unit_cost(self):
|
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,
|
self.fake.insert_lot(ts_code='002979.SZ', lot_type='BASE', qty=1,
|
||||||
|
|
@ -164,9 +164,9 @@ class CostPrecisionTests(unittest.TestCase):
|
||||||
workbook = openpyxl.load_workbook(io.BytesIO(
|
workbook = openpyxl.load_workbook(io.BytesIO(
|
||||||
publish_export.build_workbook(snapshot, publish_export._nav_series(snapshot))))
|
publish_export.build_workbook(snapshot, publish_export._nav_series(snapshot))))
|
||||||
sheet = workbook['Sheet1']
|
sheet = workbook['Sheet1']
|
||||||
self.assertEqual(sheet['K5'].value, 48.285)
|
self.assertEqual(sheet['L5'].value, 48.285)
|
||||||
self.assertEqual(sheet['G5'].value, '=ROUND(K5*L5,2)')
|
self.assertEqual(sheet['G5'].value, '=ROUND(L5*M5,2)')
|
||||||
self.assertEqual(sheet['S5'].value, '=ROUND(ROUND(M5*L5,2)-G5,2)')
|
self.assertEqual(sheet['T5'].value, '=ROUND(H5-G5,2)')
|
||||||
|
|
||||||
def test_multiple_lots_accumulate_before_half_cent_rounding(self):
|
def test_multiple_lots_accumulate_before_half_cent_rounding(self):
|
||||||
for price in (48.281, 48.284):
|
for price in (48.281, 48.284):
|
||||||
|
|
|
||||||
|
|
@ -2876,15 +2876,18 @@ def _():
|
||||||
# 2 行持仓 → 5,6 行; 小计 7; 卖出头 8; 明细 9; 小计 10; 汇总 11/12
|
# 2 行持仓 → 5,6 行; 小计 7; 卖出头 8; 明细 9; 小计 10; 汇总 11/12
|
||||||
assert ws["E5"].value == "000001" and ws["E6"].value == "600000", (
|
assert ws["E5"].value == "000001" and ws["E6"].value == "600000", (
|
||||||
ws["E5"].value, ws["E6"].value) # 按最早开仓日排序
|
ws["E5"].value, ws["E6"].value) # 按最早开仓日排序
|
||||||
assert ws["L6"].value == 2000 and ws["D5"].value == "测试账户"
|
assert ws["M6"].value == 2000 and ws["D5"].value == "测试账户"
|
||||||
assert ws["U5"].value == "=1+T5" and ws["S5"].value == "=ROUND(ROUND(M5*L5,2)-G5,2)"
|
assert [ws[f"{col}4"].value for col in 'GHI'] == ['交易金额(元)', '市值(元)', '起始时间']
|
||||||
|
assert ws["V5"].value == "=1+U5" and ws["T5"].value == "=ROUND(H5-G5,2)"
|
||||||
|
assert ws["H5"].value == "=ROUND(N5*M5,2)" and ws["H7"].value == "=SUM(H5:H6)"
|
||||||
|
assert ws["H9"].value is None and ws["H11"].value == "=H7"
|
||||||
assert ws["C8"].value == "序" + chr(10) + "号", repr(ws["C8"].value)
|
assert ws["C8"].value == "序" + chr(10) + "号", repr(ws["C8"].value)
|
||||||
assert ws["S9"].value == 987.5 and ws["T9"].value == "=IF(G9=0,0,S9/G9)"
|
assert ws["T9"].value == 987.5 and ws["U9"].value == "=IF(G9=0,0,T9/G9)"
|
||||||
assert ws["G7"].value == "=SUM(G5:G6)" and ws["G10"].value == "=SUM(G9:G9)"
|
assert ws["G7"].value == "=SUM(G5:G6)" and ws["G10"].value == "=SUM(G9:G9)"
|
||||||
assert ws["S11"].value == "=S7+S10" and ws["F12"].value.startswith("=1000000")
|
assert ws["T11"].value == "=T7+T10" and ws["F12"].value.startswith("=1000000")
|
||||||
assert ws["O12"].value == "=U11" and ws["Q12"].value == "=U11"
|
assert ws["P12"].value == "=V11" and ws["R12"].value == "=V11"
|
||||||
merges = {str(r) for r in ws.merged_cells.ranges}
|
merges = {str(r) for r in ws.merged_cells.ranges}
|
||||||
assert {"B1:T1", "B4:B7", "B8:B10", "B11:F11", "B12:E12"} <= merges, merges
|
assert {"B1:V1", "B4:B7", "B8:B10", "B11:F11", "B12:E12"} <= merges, merges
|
||||||
# 两个竖排段落标签必须都在 (模板裁剪曾把「平层卖出」丢过一次, 钉死)
|
# 两个竖排段落标签必须都在 (模板裁剪曾把「平层卖出」丢过一次, 钉死)
|
||||||
assert ws["B4"].value == "平层" + chr(10) + "持仓", repr(ws["B4"].value)
|
assert ws["B4"].value == "平层" + chr(10) + "持仓", repr(ws["B4"].value)
|
||||||
assert ws["B8"].value == "平层" + chr(10) + "卖出", repr(ws["B8"].value)
|
assert ws["B8"].value == "平层" + chr(10) + "卖出", repr(ws["B8"].value)
|
||||||
|
|
@ -2916,20 +2919,21 @@ def _():
|
||||||
open_date=d0, close_date=d1, structure="平层", cost=8.0, qty=1000,
|
open_date=d0, close_date=d1, structure="平层", cost=8.0, qty=1000,
|
||||||
settle=8.2, days=6, pnl=200.0 - 40.0 * i) for i in range(10)]
|
settle=8.2, days=6, pnl=200.0 - 40.0 * i) for i in range(10)]
|
||||||
s2 = dict(s, holdings=mkh, closed=mkc, price_missing=[], fee_resid=0.0)
|
s2 = dict(s, holdings=mkh, closed=mkc, price_missing=[], fee_resid=0.0)
|
||||||
blob2 = pub.build_workbook(s2, [{"ymd": ymd, "nav": 1.001, "pos_ratio": 0.35}])
|
blob2 = pub.build_workbook(s2, [{"ymd": int(d1.strftime('%Y%m%d')), "nav": 1.001, "pos_ratio": 0.35},
|
||||||
|
{"ymd": ymd, "nav": 1.002, "pos_ratio": 0.40}])
|
||||||
wb2 = openpyxl.load_workbook(_io.BytesIO(blob2))
|
wb2 = openpyxl.load_workbook(_io.BytesIO(blob2))
|
||||||
ws2 = wb2["Sheet1"]
|
ws2 = wb2["Sheet1"]
|
||||||
# 行位: 持仓 5..11, 小计 12, 卖出头 13, 明细 14..23, 小计 24, 存量 25, 底行 26
|
# 行位: 持仓 5..11, 小计 12, 卖出头 13, 明细 14..23, 小计 24, 存量 25, 底行 26
|
||||||
assert ws2.cell(row=24, column=7).value == "=SUM(G14:G23)", ws2.cell(row=24, column=7).value
|
assert ws2.cell(row=24, column=7).value == "=SUM(G14:G23)", ws2.cell(row=24, column=7).value
|
||||||
assert ws2.cell(row=25, column=2).value == "存量合计", ws2.cell(row=25, column=2).value
|
assert ws2.cell(row=25, column=2).value == "存量合计", ws2.cell(row=25, column=2).value
|
||||||
assert ws2.cell(row=25, column=19).value == "=S12+S24"
|
assert ws2.cell(row=25, column=20).value == "=T12+T24"
|
||||||
assert ws2.cell(row=26, column=2).value == "初始规模+已回收益后可开仓总金额"
|
assert ws2.cell(row=26, column=2).value == "初始规模+已回收益后可开仓总金额"
|
||||||
assert ws2.cell(row=26, column=17).value == "=U25"
|
assert ws2.cell(row=26, column=18).value == "=V25"
|
||||||
assert not [r0 for r0, dd in ws2.row_dimensions.items() if dd.hidden], "行不许隐藏"
|
assert not [r0 for r0, dd in ws2.row_dimensions.items() if dd.hidden], "行不许隐藏"
|
||||||
assert max(ws2.row_dimensions) <= 26, max(ws2.row_dimensions)
|
assert max(ws2.row_dimensions) <= 26, max(ws2.row_dimensions)
|
||||||
assert ws2.row_dimensions[25].height == 18.0 and ws2.row_dimensions[26].height == 40.5
|
assert ws2.row_dimensions[25].height == 18.0 and ws2.row_dimensions[26].height == 40.5
|
||||||
cfsq = sorted(str(cf.sqref) for cf in ws2.conditional_formatting)
|
cfsq = sorted(str(cf.sqref) for cf in ws2.conditional_formatting)
|
||||||
assert cfsq == sorted(["Q5:R11", "S5:S11", "Q14:S23", "S12 S24"]), cfsq
|
assert cfsq == sorted(["R5:S11", "T5:T11", "R14:T23", "T12 T24"]), cfsq
|
||||||
zf2 = _zip.ZipFile(_io.BytesIO(blob2))
|
zf2 = _zip.ZipFile(_io.BytesIO(blob2))
|
||||||
sx2 = zf2.read("xl/worksheets/sheet1.xml").decode("utf-8")
|
sx2 = zf2.read("xl/worksheets/sheet1.xml").decode("utf-8")
|
||||||
assert not _re.search('<row [^>]*hidden="1"', sx2), "导出的行带着隐藏标记"
|
assert not _re.search('<row [^>]*hidden="1"', sx2), "导出的行带着隐藏标记"
|
||||||
|
|
@ -2938,6 +2942,13 @@ def _():
|
||||||
assert 'symbol val="circle"' in cx2 and 'symbol val="diamond"' in cx2
|
assert 'symbol val="circle"' in cx2 and 'symbol val="diamond"' in cx2
|
||||||
assert '<plotVisOnly val="0"' in cx2, "隐藏单元格也必须照画"
|
assert '<plotVisOnly val="0"' in cx2, "隐藏单元格也必须照画"
|
||||||
assert cx2.count("<valAx>") == 2 # 仓位占比走副轴
|
assert cx2.count("<valAx>") == 2 # 仓位占比走副轴
|
||||||
|
chart = ws2._charts[0]
|
||||||
|
assert (chart.anchor._from.col, chart.anchor.to.col) == (1, 22)
|
||||||
|
assert chart.series[0].dLbls.showVal and chart.series[0].dLbls.numFmt == '0.0000'
|
||||||
|
assert chart.series[0].dLbls.showCatName is False and chart.series[0].dLbls.showLegendKey is False
|
||||||
|
assert chart._charts[1].series[0].dLbls is None
|
||||||
|
nav_formula = chart.series[0].val.numRef.f
|
||||||
|
assert nav_formula.endswith('$AA$30:$AA$31'), nav_formula
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue