feat: add broker investment performance
This commit is contained in:
@@ -22,6 +22,7 @@ import analyticsRouter from './routes/analytics';
|
||||
import portfolioRouter from './routes/portfolio';
|
||||
import portfolioOverviewRouter from './routes/portfolioOverview';
|
||||
import portfolioHistoryRouter from './routes/portfolioHistory';
|
||||
import portfolioPerformanceRouter from './routes/portfolioPerformance';
|
||||
|
||||
const app = express();
|
||||
app.set('trust proxy', 1);
|
||||
@@ -49,6 +50,7 @@ app.use('/api/analytics', analyticsRouter);
|
||||
app.use('/api/import/portfolio', portfolioRouter);
|
||||
app.use('/api/portfolio', portfolioOverviewRouter);
|
||||
app.use('/api/portfolio/history', portfolioHistoryRouter);
|
||||
app.use('/api/portfolio/performance', portfolioPerformanceRouter);
|
||||
|
||||
app.use(
|
||||
(
|
||||
|
||||
9
backend/src/routes/portfolioPerformance.ts
Normal file
9
backend/src/routes/portfolioPerformance.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { Router } from 'express';
|
||||
import { asyncHandler } from '../utils';
|
||||
import { getPortfolioPerformance } from '../services/portfolio';
|
||||
|
||||
const router = Router();
|
||||
router.get('/', asyncHandler(async (_req, res) => {
|
||||
res.json(await getPortfolioPerformance());
|
||||
}));
|
||||
export default router;
|
||||
@@ -2,7 +2,7 @@ import crypto from 'crypto';
|
||||
import type { PoolClient } from 'pg';
|
||||
import { pool } from '../db/pool';
|
||||
import { maskAccountNumber } from '../utils';
|
||||
import type { ImportPortfolioResponse, PortfolioFile, PortfolioHistoryResponse, PortfolioOverviewResponse, PortfolioTrade } from '@family-budget/shared';
|
||||
import type { ImportPortfolioResponse, PortfolioFile, PortfolioHistoryResponse, PortfolioOverviewResponse, PortfolioPerformanceResponse, PortfolioTrade } from '@family-budget/shared';
|
||||
|
||||
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
||||
|
||||
@@ -29,6 +29,10 @@ type PortfolioHistoryRow = {
|
||||
total_valuation: string | number | null;
|
||||
};
|
||||
|
||||
type PerformanceCashRow = { account_id: number | string; alias: string | null; bank: string; account_number: string; amount_signed: number | string; description: string };
|
||||
type PerformanceTradeRow = { account_id: number | string; side: string; quantity: string | number; settlement_amount: string | number | null; settlement_commission: string | number | null; trade_commission: string | number | null; isin: string | null; instrument: string };
|
||||
type PerformancePositionRow = { account_id: number | string; quantity: string | number; valuation: string | number | null; isin: string | null; instrument: string };
|
||||
|
||||
function decimalValue(value: unknown, field: string, required = false): string | null {
|
||||
if (value == null || value === '') {
|
||||
if (required) throw new Error(`${field} is required`);
|
||||
@@ -212,3 +216,80 @@ export async function getPortfolioHistory(): Promise<PortfolioHistoryResponse> {
|
||||
);
|
||||
return toPortfolioHistory(rows);
|
||||
}
|
||||
|
||||
type Lot = { quantity: number; cost: number };
|
||||
|
||||
export function calculatePortfolioTradeResults(trades: PerformanceTradeRow[], positions: PerformancePositionRow[]): Map<number, { fees: number; realized: number; unrealized: number | null }> {
|
||||
const result = new Map<number, { fees: number; realized: number; unrealized: number | null }>();
|
||||
const lots = new Map<string, Lot[]>();
|
||||
for (const trade of trades) {
|
||||
const accountId = Number(trade.account_id);
|
||||
const current = result.get(accountId) ?? { fees: 0, realized: 0, unrealized: null };
|
||||
const quantity = Number(trade.quantity);
|
||||
const amount = Number(trade.settlement_amount ?? 0);
|
||||
const fees = Number(trade.settlement_commission ?? 0) + Number(trade.trade_commission ?? 0);
|
||||
current.fees += fees;
|
||||
const key = `${accountId}:${trade.isin ?? trade.instrument}`;
|
||||
const queue = lots.get(key) ?? [];
|
||||
if (/продаж/i.test(trade.side)) {
|
||||
let remaining = quantity;
|
||||
let matchedCost = 0;
|
||||
while (remaining > 0 && queue.length > 0) {
|
||||
const lot = queue[0];
|
||||
const used = Math.min(remaining, lot.quantity);
|
||||
const unitCost = lot.cost / lot.quantity;
|
||||
matchedCost += used * unitCost;
|
||||
lot.cost -= used * unitCost;
|
||||
lot.quantity -= used;
|
||||
remaining -= used;
|
||||
if (lot.quantity <= 0) queue.shift();
|
||||
}
|
||||
const matched = quantity - remaining;
|
||||
current.realized += matched > 0 ? (amount - fees) * (matched / quantity) - matchedCost : 0;
|
||||
} else if (/покуп/i.test(trade.side) && quantity > 0) {
|
||||
queue.push({ quantity, cost: amount + fees });
|
||||
}
|
||||
lots.set(key, queue);
|
||||
result.set(accountId, current);
|
||||
}
|
||||
const positionCost = new Map<string, number>();
|
||||
for (const [key, queue] of lots) positionCost.set(key, queue.reduce((sum, lot) => sum + lot.cost, 0));
|
||||
for (const position of positions) {
|
||||
const accountId = Number(position.account_id);
|
||||
const current = result.get(accountId) ?? { fees: 0, realized: 0, unrealized: 0 };
|
||||
if (position.valuation !== null) {
|
||||
const key = `${accountId}:${position.isin ?? position.instrument}`;
|
||||
current.unrealized = (current.unrealized ?? 0) + Number(position.valuation) - (positionCost.get(key) ?? 0);
|
||||
}
|
||||
result.set(accountId, current);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function getPortfolioPerformance(): Promise<PortfolioPerformanceResponse> {
|
||||
const [cashResult, tradeResult, positionResult] = await Promise.all([
|
||||
pool.query<PerformanceCashRow>(`SELECT a.id AS account_id, a.alias, a.bank, a.account_number, t.amount_signed, t.description FROM accounts a JOIN transactions t ON t.account_id = a.id WHERE a.account_type IN ('brokerage', 'iis') ORDER BY a.id, t.operation_at, t.id`),
|
||||
pool.query<PerformanceTradeRow>(`SELECT account_id, side, quantity, settlement_amount, settlement_commission, trade_commission, isin, instrument FROM portfolio_trades ORDER BY account_id, concluded_at, id`),
|
||||
pool.query<PerformancePositionRow>(`SELECT r.account_id, p.quantity, p.valuation, p.isin, p.instrument FROM portfolio_reports r JOIN portfolio_positions p ON p.report_id = r.id JOIN LATERAL (SELECT id FROM portfolio_reports WHERE account_id = r.account_id ORDER BY report_period_to DESC, imported_at DESC, id DESC LIMIT 1) latest ON latest.id = r.id`),
|
||||
]);
|
||||
const tradeMap = calculatePortfolioTradeResults(tradeResult.rows, positionResult.rows);
|
||||
const accounts = new Map<number, PortfolioPerformanceResponse['accounts'][number]>();
|
||||
for (const row of cashResult.rows) {
|
||||
const accountId = Number(row.account_id);
|
||||
const account = accounts.get(accountId) ?? { accountId, accountName: row.alias || `${row.bank} · ${maskAccountNumber(row.account_number)}`, contributions: 0, withdrawals: 0, income: 0, fees: 0, realizedResult: 0, unrealizedResult: null };
|
||||
const amount = Number(row.amount_signed);
|
||||
const description = row.description.toLowerCase();
|
||||
if (amount > 0 && /дивиденд|купон|процент/.test(description)) account.income += amount;
|
||||
else if (amount > 0 && description.includes('зачисление денежных средств')) account.contributions += amount;
|
||||
else if (amount < 0 && /вывод денежных средств|вывод дс/.test(description) && !description.includes('под нерассчитанные сделки')) account.withdrawals += -amount;
|
||||
accounts.set(accountId, account);
|
||||
}
|
||||
for (const [accountId, values] of tradeMap) {
|
||||
const account = accounts.get(accountId) ?? { accountId, accountName: `Счёт ${accountId}`, contributions: 0, withdrawals: 0, income: 0, fees: 0, realizedResult: 0, unrealizedResult: null };
|
||||
account.fees = Math.round(values.fees * 100);
|
||||
account.realizedResult = Math.round(values.realized * 100);
|
||||
account.unrealizedResult = values.unrealized === null ? null : Math.round(values.unrealized * 100);
|
||||
accounts.set(accountId, account);
|
||||
}
|
||||
return { accounts: [...accounts.values()] };
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { toPortfolioHistory, toPortfolioOverview } from './portfolio';
|
||||
import { calculatePortfolioTradeResults, toPortfolioHistory, toPortfolioOverview } from './portfolio';
|
||||
|
||||
const result = toPortfolioOverview([
|
||||
{ account_id: '1', alias: 'ИИС', bank: 'ВТБ', account_number: '123456', report_period_to: '2026-08-26', total_valuation: '150.50', instrument: 'Облигация', isin: 'RU0000000001', quantity: '1', price: '100', valuation: '100' },
|
||||
@@ -17,3 +17,12 @@ const history = toPortfolioHistory([
|
||||
]);
|
||||
assert.deepEqual(history.accounts[0].points.map((point) => point.totalValuation), ['100', '150.50']);
|
||||
console.log('portfolio history: OK');
|
||||
|
||||
const tradeResults = calculatePortfolioTradeResults([
|
||||
{ account_id: 1, side: 'Покупка', quantity: '2', settlement_amount: '200', settlement_commission: '1', trade_commission: '1', isin: 'RU1', instrument: 'Фонд' },
|
||||
{ account_id: 1, side: 'Продажа', quantity: '1', settlement_amount: '150', settlement_commission: '1', trade_commission: '0', isin: 'RU1', instrument: 'Фонд' },
|
||||
], [{ account_id: 1, quantity: '1', valuation: '130', isin: 'RU1', instrument: 'Фонд' }]);
|
||||
assert.equal(tradeResults.get(1)?.fees, 3);
|
||||
assert.equal(tradeResults.get(1)?.realized, 48);
|
||||
assert.equal(tradeResults.get(1)?.unrealized, 29);
|
||||
console.log('portfolio performance: OK');
|
||||
|
||||
Reference in New Issue
Block a user