1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
// 投入口径 reporting 推导函数测试(Leader 第二轮返工后追加任务 A3)。
// 断言锚点 = 生产现网 run 26e9c9ab-2fad-4a7d-8190-2a7134a11f76 的真实账目:
// 累计投入 12029.09 / 最终持仓估值 10846.00 / 投入回报率 -9.84%。
// 口径:投入 = 首日 cash − 末日 cash;估值 = Σ 末日 positions × closes;
// 回报 = 估值 / 投入 − 1。不含初始账户闲置现金。
import { describe, expect, it } from 'vitest';
import { capitalReporting, fmtInvestmentPct } from './capitalMetrics';
// 忠实于现网该 run 的首末两行(中间行与本口径无关)。
const fixture = {
equity: [
{ date: '2025-09-18', equity: 100000.0, cash: 100000.0, closes: { '159399': 1.127 }, positions: { '159399': 0 } },
{ date: '2026-09-17', equity: 98816.91045543, cash: 87970.91045543001, closes: { '159399': 0.986 }, positions: { '159399': 11000 } }
]
} as const;
describe('capitalReporting(现网 run 26e9c9ab 真实账目锚点)', () => {
it('累计投入 = 首日 cash − 末日 cash,保留 2 位', () => {
const c = capitalReporting(fixture as never);
expect(c.invested).toBeCloseTo(12029.09, 2);
});
it('最终持仓估值 = Σ 末日 positions × closes(10846.00)', () => {
const c = capitalReporting(fixture as never);
expect(c.holdingValue).toBeCloseTo(10846.0, 2);
});
it('投入回报率 = 估值 / 投入 − 1,带正负号与百分号(-9.84%)', () => {
const c = capitalReporting(fixture as never);
expect(c.returnPct).toBe('-9.84%');
});
it('多持仓键:多个 symbol 的市值求和', () => {
const multi = {
equity: [
{ date: 'd0', equity: 50000, cash: 50000 },
{ date: 'd1', equity: 50600, cash: 30000, closes: { A: 10.0, B: 2.0 }, positions: { A: 2000, B: 300 } }
]
} as never;
const c = capitalReporting(multi);
expect(c.invested).toBeCloseTo(20000, 2);
expect(c.holdingValue).toBeCloseTo(20000 + 600, 2);
expect(c.returnPct).toBe('+3.00%');
});
it('无投入(未建仓)时回报为 null,不除零', () => {
const flat = { equity: [{ date: 'd0', equity: 100000, cash: 100000 }] } as never;
const c = capitalReporting(flat);
expect(c.invested).toBeCloseTo(0, 2);
expect(c.holdingValue).toBeCloseTo(0, 2);
expect(c.returnPct).toBeNull();
});
it('空 equity 返回全 null,UI 可渲染占位', () => {
const c = capitalReporting({ equity: [] } as never);
expect(c.invested).toBeNull();
expect(c.holdingValue).toBeNull();
expect(c.returnPct).toBeNull();
});
});
describe('fmtInvestmentPct(正负号与百分号)', () => {
it('负值带负号', () => {
expect(fmtInvestmentPct(-0.098435)).toBe('-9.84%');
});
it('正值带加号', () => {
expect(fmtInvestmentPct(0.03)).toBe('+3.00%');
});
it('四舍五入两位', () => {
expect(fmtInvestmentPct(0.045849)).toBe('+4.58%');
});
});
|