fix: avoid incomplete unrealized result
This commit is contained in:
@@ -252,17 +252,30 @@ export function calculatePortfolioTradeResults(trades: PerformanceTradeRow[], po
|
|||||||
lots.set(key, queue);
|
lots.set(key, queue);
|
||||||
result.set(accountId, current);
|
result.set(accountId, current);
|
||||||
}
|
}
|
||||||
const positionCost = new Map<string, number>();
|
const incomplete = new Set<number>();
|
||||||
for (const [key, queue] of lots) positionCost.set(key, queue.reduce((sum, lot) => sum + lot.cost, 0));
|
|
||||||
for (const position of positions) {
|
for (const position of positions) {
|
||||||
const accountId = Number(position.account_id);
|
const accountId = Number(position.account_id);
|
||||||
const current = result.get(accountId) ?? { fees: 0, realized: 0, unrealized: 0 };
|
const current = result.get(accountId) ?? { fees: 0, realized: 0, unrealized: 0 };
|
||||||
if (position.valuation !== null) {
|
if (position.valuation !== null) {
|
||||||
const key = `${accountId}:${position.isin ?? position.instrument}`;
|
const key = `${accountId}:${position.isin ?? position.instrument}`;
|
||||||
current.unrealized = (current.unrealized ?? 0) + Number(position.valuation) - (positionCost.get(key) ?? 0);
|
const queue = lots.get(key) ?? [];
|
||||||
|
let remaining = Number(position.quantity);
|
||||||
|
let cost = 0;
|
||||||
|
for (const lot of queue) {
|
||||||
|
if (remaining <= 0) break;
|
||||||
|
const used = Math.min(remaining, lot.quantity);
|
||||||
|
cost += used * (lot.cost / lot.quantity);
|
||||||
|
remaining -= used;
|
||||||
|
}
|
||||||
|
if (remaining > 0.0000001) incomplete.add(accountId);
|
||||||
|
else if (!incomplete.has(accountId)) current.unrealized = (current.unrealized ?? 0) + Number(position.valuation) - cost;
|
||||||
}
|
}
|
||||||
result.set(accountId, current);
|
result.set(accountId, current);
|
||||||
}
|
}
|
||||||
|
for (const accountId of incomplete) {
|
||||||
|
const current = result.get(accountId);
|
||||||
|
if (current) current.unrealized = null;
|
||||||
|
}
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user